List of usage examples for javax.sound.sampled AudioSystem getAudioInputStream
public static AudioInputStream getAudioInputStream(final File file) throws UnsupportedAudioFileException, IOException
From source file:org.sipfoundry.voicemail.VmMessage.java
/** * Combine two wav files into one bigger one * /* www. ja v a 2 s . c om*/ * @param newFile * @param orig1 * @param orig2 * @throws Exception */ static void concatAudio(File newFile, File orig1, File orig2) throws Exception { String operation = "dunno"; try { operation = "getting AudioInputStream from " + orig1.getPath(); AudioInputStream clip1 = AudioSystem.getAudioInputStream(orig1); operation = "getting AudioInputStream from " + orig2.getPath(); AudioInputStream clip2 = AudioSystem.getAudioInputStream(orig2); operation = "building SequnceInputStream"; AudioInputStream concatStream = new AudioInputStream(new SequenceInputStream(clip1, clip2), clip1.getFormat(), clip1.getFrameLength() + clip2.getFrameLength()); operation = "writing SequnceInputStream to " + newFile.getPath(); AudioSystem.write(concatStream, AudioFileFormat.Type.WAVE, newFile); LOG.info("VmMessage::concatAudio created combined file " + newFile.getPath()); } catch (Exception e) { String trouble = "VmMessage::concatAudio Problem while " + operation; // LOG.error(trouble, e); throw new Exception(trouble, e); } }
From source file:gui.EventReader.java
@Override public void run() { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); //HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet( //"https://api.guildwars2.com/v1/events.json?world_id=" "http://gw2eventer.sourceforge.net/api/events.php?world_id=" + this.worldID); HttpResponse response;/* w w w . j a v a2 s . co m*/ String line = ""; String out = ""; while (!isInterrupted()) { try { this.labelWorking.setText(this.workingString); try { response = client.execute(request); if (response.getStatusLine().toString().contains("200")) { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8"))); line = ""; out = ""; while ((line = rd.readLine()) != null) { out = out + line; } } else { // http error request.releaseConnection(); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; } } catch (IOException | IllegalStateException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); request.releaseConnection(); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; //this.interrupt(); } request.releaseConnection(); JSONParser parser = new JSONParser(); Object obj; this.result.clear(); HashMap mehrfachEvents = new HashMap(); playSoundsList.clear(); this.overlayGui.clearActive(); String toolTip; try { obj = parser.parse(out); for (int i = 0; i < this.eventLabels.size(); i++) { JLabel iter = (JLabel) this.eventLabels.get(i); iter.setEnabled(false); iter.setForeground(Color.green); } for (Iterator iterator = ((JSONObject) obj).values().iterator(); iterator.hasNext();) { JSONArray arrayNew = (JSONArray) iterator.next(); for (int i = 0; i < arrayNew.size(); i++) { JSONObject obj2 = (JSONObject) arrayNew.get(i); if (obj2.get("event_id") != null) { String event = (String) obj2.get("event_id"); if (this.events.containsKey(event)) { //System.out.println("debug: " + event + "\n"); this.result.add(obj2.get("event_id")); int indexEvent = Integer.parseInt(((String[]) this.events.get(event))[0]); String eventPercent = ((String[]) this.events.get(event))[1]; String eventWav = ((String[]) this.events.get(event))[2]; String eventName = ((String[]) this.events.get(event))[3]; JLabel activeLabel = (JLabel) this.eventLabels.get(indexEvent - 1); JLabel activeLabelTimer = (JLabel) this.eventLabelsTimer.get(indexEvent - 1); int activeLabelInt = indexEvent - 1; String tmpEventName = eventPercent.substring(0, 1); Date dateNow = new Date(); long stampNow = dateNow.getTime(); if (this.timerStamps[activeLabelInt] != null) { long oldTimestamp = this.timerStamps[activeLabelInt].getTime(); long minsdiff = ((stampNow - oldTimestamp) / 1000 / 60); if (minsdiff >= 30) { activeLabelTimer.setEnabled(true); } else { activeLabelTimer.setEnabled(false); } if (minsdiff >= 60) { activeLabelTimer.setForeground(Color.red); } else { activeLabelTimer.setForeground(Color.green); } activeLabelTimer.setText(minsdiff + " mins (B)"); } /* if (activeLabel != null) { if (activeLabel.getToolTipText() != null) { if (activeLabel.getToolTipText().equals("")) { // null pointer?? activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id"))); } } }*/ if (obj2.get("state").equals("Active")) { activeLabel.setEnabled(true); //activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id"))); toolTip = activeLabel.getToolTipText(); if (toolTip != null) { if (toolTip.length() > 35) { toolTip = toolTip.substring(0, 35) + "..."; } } else { toolTip = ""; } if (tmpEventName.equals("B")) { this.markedBs[activeLabelInt] = true; activeLabelTimer.setVisible(false); this.timerStamps[activeLabelInt] = null; if (this.eventPlaySounds[activeLabelInt][2]) { if (!this.overlayGui.containsActiveB(eventName)) { this.overlayGui.addActiveB(eventName, "yellow", activeLabelInt); } } else { if (!this.overlayGui.containsActiveB(eventName)) { this.overlayGui.addActiveB(eventName, "green", activeLabelInt); } } } else { if (this.eventPlaySounds[activeLabelInt][2]) { if (!this.overlayGui.containsActivePre(eventName)) { this.overlayGui.addActivePreEvent(eventName, "yellow", activeLabelInt); } } else { if (!this.overlayGui.containsActivePre(eventName)) { this.overlayGui.addActivePreEvent(eventName, "green", activeLabelInt); } } } //activeLabel.setSize(100, activeLabel.getSize().height); //activeLabel.setText(eventPercent); URL url = this.getClass().getClassLoader() .getResource("media/sounds/" + eventWav + ".wav"); if (!playSoundsList.containsKey(url)) { if (!this.eventPlaySounds[activeLabelInt][2]) { if (tmpEventName.equals("B")) { if (this.eventPlaySounds[activeLabelInt][1]) { playSoundsList.put(url, activeLabel); } } else { if (this.eventPlaySounds[activeLabelInt][0]) { playSoundsList.put(url, activeLabel); } } } else { activeLabel.setForeground(Color.YELLOW); } } if (mehrfachEvents.containsKey(activeLabel)) { ((ArrayList) mehrfachEvents.get(activeLabel)).add(tmpEventName); } else { ArrayList tmpListe = new ArrayList(); tmpListe.add(tmpEventName); mehrfachEvents.put(activeLabel, tmpListe); } } else { if (tmpEventName.equals("B")) { if (this.markedBs[activeLabelInt]) { this.timerStamps[activeLabelInt] = dateNow; this.markedBs[activeLabelInt] = false; activeLabelTimer.setVisible(true); activeLabelTimer.setText("0 mins (B)"); } } } } } } } Iterator it = mehrfachEvents.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); JLabel label = (JLabel) pairs.getKey(); ArrayList liste = (ArrayList) pairs.getValue(); String outString = null; Collections.sort(liste, new Comparator<String>() { public int compare(String f1, String f2) { return -f1.toString().compareTo(f2.toString()); } }); for (int i = 0; i < liste.size(); i++) { if (outString == null) { outString = (String) liste.get(i); } else { outString += ", " + (String) liste.get(i); } } label.setText(outString); it.remove(); } this.labelServer.setOpaque(true); this.labelServer.setOpaque(false); this.labelServer.setEnabled(false); this.labelServer.setText(""); this.labelServer.setText(this.worldName); this.labelWorking.setVisible(false); this.refreshSelector.setEnabled(true); this.workingButton.setEnabled(true); this.jComboBoxLanguage.setEnabled(true); this.overlayGui.renderActive(); if (playSounds) { this.playThread = new Thread() { @Override public void run() { Iterator it = playSoundsList.entrySet().iterator(); while (it.hasNext() && !isInterrupted()) { AudioInputStream audioIn; Map.Entry pairs = (Map.Entry) it.next(); JLabel label = (JLabel) pairs.getValue(); try { playSoundsCurrent = (URL) pairs.getKey(); audioIn = AudioSystem.getAudioInputStream(playSoundsCurrent); Clip clip = null; String tmp = label.getText(); try { //label.setText(">" + tmp); //label.setText("<HTML><U>" + tmp + "<U><HTML>"); label.setForeground(Color.red); //Font font = label.getFont(); //Map attributes = font.getAttributes(); //attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); //label.setFont(font.deriveFont(attributes)); clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (LineUnavailableException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } finally { try { audioIn.close(); } catch (IOException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } } try { Thread.sleep(2000); //label.setText(tmp); label.setForeground(Color.green); } catch (InterruptedException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); this.interrupt(); //?? } } catch (UnsupportedAudioFileException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex); } it.remove(); } } }; this.playThread.start(); this.playThread.join(); } } catch (ParseException ex) { Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex); this.refreshSelector.setEnabled(false); this.workingButton.setEnabled(false); this.jComboBoxLanguage.setEnabled(false); this.labelWorking.setText("connection error. retrying in... 10."); this.labelWorking.setVisible(true); Thread.sleep(10000); continue; } if (this.autoRefresh) { Thread.sleep(this.sleepTime * 1000); } else { this.interrupt(); } } catch (InterruptedException ex) { Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex); this.interrupt(); } } }
From source file:com.xyphos.vmtgen.GUI.java
private void generateVMT() { if (-1 == lstFiles.getSelectedIndex()) { return;/*from w ww . j a va 2s . co m*/ } String value = lstFiles.getSelectedValue().toString(); String path = FilenameUtils .separatorsToSystem(FilenameUtils.concat(workPath, FilenameUtils.getBaseName(value) + ".VMT")); File fileVMT = new File(path); try (PrintWriter out = new PrintWriter(fileVMT, "UTF-8")) { value = (0 == cmbShader.getSelectedIndex()) ? txtShader.getText() : cmbShader.getSelectedItem().toString(); // write the shader out.printf("\"%s\"%n{%n", value); writeSpinner(out, nudAlpha, 1F, "$alpha", 4); writeSpinner(out, nudEnvMapContrast, 0F, "$envMapContrast", 3); writeSpinner(out, nudEnvMapContrast, 0F, "$envMapSaturation", 2); writeSpinner(out, nudEnvMapFrame, 0, "$envMapFrame", 3); // write surfaces int index = cmbSurface1.getSelectedIndex(); if (0 != index) { value = (1 == index) ? txtSurface1.getText() : cmbSurface1.getSelectedItem().toString(); writeKeyValue(true, out, "$surfaceProp", value, 3); } index = cmbSurface2.getSelectedIndex(); if (0 != index) { value = (1 == index) ? txtSurface2.getText() : cmbSurface2.getSelectedItem().toString(); writeKeyValue(true, out, "$surfaceProp2", value, 3); } writeKeyValue(!(value = txtKeywords.getText()).isEmpty(), out, "%keywords", value, 3); writeKeyValue(!(value = txtToolTexture.getText()).isEmpty(), out, "%toolTexture", value, 3); writeKeyValue(!(value = txtBaseTexture1.getText()).isEmpty(), out, "$baseTexture", value, 3); writeKeyValue(!(value = txtBaseTexture2.getText()).isEmpty(), out, "$baseTexture2", value, 3); writeKeyValue(!(value = txtDetailTexture.getText()).isEmpty(), out, "$detail", value, 4); writeKeyValue(!(value = txtBumpMap1.getText()).isEmpty(), out, "$bumpMap", value, 3); writeKeyValue(!(value = txtBumpMap2.getText()).isEmpty(), out, "$bumpMap2", value, 3); writeKeyValue(!(value = txtEnvMap.getText()).isEmpty(), out, "$envMap", value, 3); writeKeyValue(!(value = txtEnvMapMask.getText()).isEmpty(), out, "$envMapMask", value, 3); writeKeyValue(!(value = txtNormalMap.getText()).isEmpty(), out, "$normalMap", value, 3); writeKeyValue(!(value = txtDuDvMap.getText()).isEmpty(), out, "$DuDvMap", value, 3); value = "1"; writeKeyValue(chkFlagAdditive.isSelected(), out, "$additive", value, 3); writeKeyValue(chkFlagAlphaTest.isSelected(), out, "$alphaTest", value, 3); writeKeyValue(chkFlagIgnoreZ.isSelected(), out, "$ignoreZ", value, 3); writeKeyValue(chkFlagNoCull.isSelected(), out, "$noCull", value, 4); writeKeyValue(chkFlagNoDecal.isSelected(), out, "$noDecal", value, 3); writeKeyValue(chkFlagNoLOD.isSelected(), out, "$noLOD", value, 3); writeKeyValue(chkFlagPhong.isSelected(), out, "$phong", value, 4); writeKeyValue(chkFlagSelfIllum.isSelected(), out, "$selfIllum", value, 3); writeKeyValue(chkFlagTranslucent.isSelected(), out, "$translucent", value, 3); writeKeyValue(chkFlagVertexAlpha.isSelected(), out, "$vertexAlpha", value, 3); writeKeyValue(chkFlagVertexColor.isSelected(), out, "$vertexColor", value, 3); writeKeyValue(chkCompileClip.isSelected(), out, "%compileClip", value, 3); writeKeyValue(chkCompileDetail.isSelected(), out, "%compileDetail", value, 3); writeKeyValue(chkCompileFog.isSelected(), out, "%compileFog", value, 3); writeKeyValue(chkCompileHint.isSelected(), out, "%compileHint", value, 3); writeKeyValue(chkCompileLadder.isSelected(), out, "%compileLadder", value, 3); writeKeyValue(chkCompileNoDraw.isSelected(), out, "%compileNoDraw", value, 3); writeKeyValue(chkCompileNoLight.isSelected(), out, "%compileNoLight", value, 3); writeKeyValue(chkCompileNonSolid.isSelected(), out, "%compileNonSolid", value, 2); writeKeyValue(chkCompileNpcClip.isSelected(), out, "%compileNpcClip", value, 3); writeKeyValue(chkCompilePassBullets.isSelected(), out, "%compilePassBullets", value, 2); writeKeyValue(chkCompilePlayerClip.isSelected(), out, "%compilePlayerClip", value, 2); writeKeyValue(chkCompilePlayerControlClip.isSelected(), out, "%compilePlayerControlClip", value, 2); writeKeyValue(chkCompileSkip.isSelected(), out, "%compileSkip", value, 3); writeKeyValue(chkCompileSky.isSelected(), out, "%compileSky", value, 3); writeKeyValue(chkCompileTrigger.isSelected(), out, "%compileTrigger", value, 3); // animation code if (animated) { value = nudFrameRate.getValue().toString(); out.printf("%n\t\"proxies\"%n"); out.printf("\t{%n"); out.printf("\t\t\"animatedTexture\"%n"); out.printf("\t\t{%n"); out.printf("\t\t\t\"animatedTextureVar\"\t\t\"$baseTexture\"%n"); out.printf("\t\t\t\"animatedTextureFrameNumVar\"\t\"$frame\"%n"); out.printf("\t\t\t\"animatedTextureFrameRate\" \t\"%s\"%n", value); out.printf("\t\t}%n"); out.printf("\t}%n"); } out.print("}"); out.flush(); try { URL url = this.getClass().getClassLoader().getResource("blip.wav"); AudioInputStream audioIn = AudioSystem.getAudioInputStream(url); clipBlip = AudioSystem.getClip(); clipBlip.open(audioIn); clipBlip.start(); } catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) { logger.log(Level.SEVERE, null, ex); } } catch (FileNotFoundException | UnsupportedEncodingException ex) { logger.log(Level.SEVERE, null, ex); } }
From source file:edu.cuny.qc.speech.AuToBI.PitchExtractor.java
public static void main(String[] args) { File file = new File(args[0]); AudioInputStream soundIn = null; try {//from w ww. j a v a 2 s . co m soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file))); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } WavReader reader = new WavReader(); WavData wav; try { if (args.length > 1) { wav = reader.read(soundIn, Double.parseDouble(args[1]), Double.parseDouble(args[2])); } else { wav = reader.read(soundIn); } System.out.println(wav.sampleRate); System.out.println(wav.sampleSize); System.out.println(wav.getFrameSize()); System.out.println(wav.getDuration()); System.out.println(wav.getNumSamples()); PitchExtractor pitchExtractor = new PitchExtractor(wav); PitchContour pitch = (PitchContour) pitchExtractor.soundToPitch(); System.out.println("pitch points:" + pitch.size()); for (int i = 0; i < pitch.size(); ++i) { System.out.println("point[" + i + "]: " + pitch.get(i) + " -- " + pitch.timeFromIndex(i) + ":" + pitch.getStrength(i)); } } catch (AuToBIException e) { e.printStackTrace(); } }
From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java
/** * Plays a sound.//from w w w . j ava2s. com * * @param fileName * The file name of the sound to play. * @return The sound Object. */ public static Object playSound(final String fileName) { try { if (StringUtils.endsWithIgnoreCase(fileName, ".mid")) { final Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); final InputStream midiFile = new FileInputStream(fileName); sequencer.setSequence(MidiSystem.getSequence(midiFile)); sequencer.start(); new Thread("Reminder MIDI sequencer") { @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (sequencer.isRunning()) { try { Thread.sleep(100); } catch (Exception ee) { // ignore } } try { sequencer.close(); midiFile.close(); } catch (Exception ee) { // ignore } } }.start(); return sequencer; } else { final AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName)); final AudioFormat format = ais.getFormat(); final DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (AudioSystem.isLineSupported(info)) { final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start(); new Thread("Reminder audio playing") { private boolean stopped; @Override public void run() { byte[] myData = new byte[1024 * format.getFrameSize()]; int numBytesToRead = myData.length; int numBytesRead = 0; int total = 0; int totalToRead = (int) (format.getFrameSize() * ais.getFrameLength()); stopped = false; line.addLineListener(new LineListener() { public void update(LineEvent event) { if (line != null && !line.isRunning()) { stopped = true; line.close(); try { ais.close(); } catch (Exception ee) { // ignore } } } }); try { while (total < totalToRead && !stopped) { numBytesRead = ais.read(myData, 0, numBytesToRead); if (numBytesRead == -1) { break; } total += numBytesRead; line.write(myData, 0, numBytesRead); } } catch (Exception e) { } line.drain(); line.stop(); } }.start(); return line; } else { URL url = new File(fileName).toURI().toURL(); AudioClip clip = Applet.newAudioClip(url); clip.play(); } } } catch (Exception e) { e.printStackTrace(); if ((new File(fileName)).isFile()) { URL url; try { url = new File(fileName).toURI().toURL(); AudioClip clip = Applet.newAudioClip(url); clip.play(); } catch (MalformedURLException e1) { } } else { String msg = mLocalizer.msg("error.1", "Error loading reminder sound file!\n({0})", fileName); JOptionPane.showMessageDialog(UiUtilities.getBestDialogParent(MainFrame.getInstance()), msg, Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE); } } return null; }
From source file:ca.sqlpower.dao.SPPersisterListener.java
/** * Does the actual commit when the transaction count reaches 0. This ensures * the persist calls are contained in a transaction if a lone change comes * through. This also allows us to roll back changes if an exception comes * from the server./*from w w w . ja va 2s . co m*/ * * @throws SPPersistenceException */ private void commit() throws SPPersistenceException { logger.debug("commit(): transactionCount = " + transactionCount); if (transactionCount == 1) { try { logger.debug("Calling commit..."); //If nothing actually changed in the transaction do not send //the begin and commit to reduce server traffic. if (objectsToRemove.isEmpty() && persistedObjects.isEmpty() && persistedProperties.isEmpty()) return; target.begin(); commitRemovals(); commitObjects(); commitProperties(); target.commit(); logger.debug("...commit completed."); if (logger.isDebugEnabled()) { try { final Clip clip = AudioSystem.getClip(); clip.open(AudioSystem .getAudioInputStream(getClass().getResource("/sounds/transaction_complete.wav"))); clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType().equals(LineEvent.Type.STOP)) { logger.debug("Stopping sound"); clip.close(); } } }); clip.start(); } catch (Exception ex) { logger.debug("A transaction committed but we cannot play the commit sound.", ex); } } } catch (Throwable t) { logger.warn("Rolling back due to " + t, t); this.rollback(); if (t instanceof SPPersistenceException) throw (SPPersistenceException) t; if (t instanceof FriendlyRuntimeSPPersistenceException) throw (FriendlyRuntimeSPPersistenceException) t; throw new SPPersistenceException(null, t); } finally { clear(); this.transactionCount = 0; } } else { transactionCount--; } }
From source file:org.scantegrity.scanner.Scanner.java
private static void playAudioClip(int p_numTimes) { /*//from w ww . j a v a 2 s . c om * Threaded Code....sigsegv when run * / if(c_audioThread != null && c_audioThread.isAlive()) { try { c_audioThread.join(2000); } catch (InterruptedException e) { c_log.log(Level.SEVERE, "Could not wait for previous sound thread."); } } c_audioThread = new Thread(new AudioFile(c_soundFile, p_numTimes)); c_audioThread.start(); /* * End threaded Code */ AudioInputStream l_stream = null; try { l_stream = AudioSystem.getAudioInputStream(new File(c_soundFileName)); } catch (UnsupportedAudioFileException e_uaf) { c_log.log(Level.WARNING, "Unsupported Audio File"); return; } catch (IOException e1) { c_log.log(Level.WARNING, "Could not Open Audio File"); return; } AudioFormat l_format = l_stream.getFormat(); Clip l_dataLine = null; DataLine.Info l_info = new DataLine.Info(Clip.class, l_format); if (!AudioSystem.isLineSupported(l_info)) { c_log.log(Level.WARNING, "Audio Line is not supported"); } try { l_dataLine = (Clip) AudioSystem.getLine(l_info); l_dataLine.open(l_stream); } catch (LineUnavailableException ex) { c_log.log(Level.WARNING, "Audio Line is unavailable."); } catch (IOException e) { c_log.log(Level.WARNING, "Cannot playback Audio, IO Exception."); } l_dataLine.loop(p_numTimes); try { Thread.sleep(160 * (p_numTimes + 1)); } catch (InterruptedException e) { c_log.log(Level.WARNING, "Could not sleep the audio player thread."); } l_dataLine.close(); }
From source file:com.skratchdot.electribe.model.esx.impl.SampleImpl.java
/** * @param file/*w ww . j av a 2 s. c om*/ * @throws EsxException */ protected SampleImpl(File file) throws EsxException { super(); init(); // Declare our streams and formats AudioFormat audioFormatEncoded; AudioFormat audioFormatDecoded; AudioInputStream audioInputStreamEncoded; AudioInputStream audioInputStreamDecoded; try { // Initialize our streams and formats audioInputStreamEncoded = AudioSystem.getAudioInputStream(file); audioFormatEncoded = audioInputStreamEncoded.getFormat(); audioFormatDecoded = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormatEncoded.getSampleRate(), 16, audioFormatEncoded.getChannels(), audioFormatEncoded.getChannels() * 2, audioFormatEncoded.getSampleRate(), true); audioInputStreamDecoded = AudioSystem.getAudioInputStream(audioFormatDecoded, audioInputStreamEncoded); // We have a decoded stereo audio stream // Now we need to get the stream info into a list we can manipulate byte[] audioData = new byte[4096]; int nBytesRead = 0; long nTotalBytesRead = 0; List<Byte> audioDataListChannel1 = new ArrayList<Byte>(); List<Byte> audioDataListChannel2 = new ArrayList<Byte>(); boolean isAudioDataStereo = false; // Set isAudioDataStereo if (audioFormatEncoded.getChannels() == 1) { isAudioDataStereo = false; } else if (audioFormatEncoded.getChannels() == 2) { isAudioDataStereo = true; } else { throw new EsxException("Sample has too many channels: " + file.getAbsolutePath()); } // Convert stream to list. This needs to be optimized. Converting // a byte at a time is probably too slow... while (nBytesRead >= 0) { nBytesRead = audioInputStreamDecoded.read(audioData, 0, audioData.length); // If we aren't at the end of the stream if (nBytesRead > 0) { for (int i = 0; i < nBytesRead; i++) { // MONO if (!isAudioDataStereo) { audioDataListChannel1.add(audioData[i]); audioDataListChannel2.add(audioData[i]); } // STEREO (LEFT) else if (nTotalBytesRead % 4 < 2) { audioDataListChannel1.add(audioData[i]); } // STEREO (RIGHT) else { audioDataListChannel2.add(audioData[i]); } // Update the total amount of bytes we've read nTotalBytesRead++; } } // Throw Exception if sample is too big if (nTotalBytesRead > EsxUtil.MAX_SAMPLE_MEM_IN_BYTES) { throw new EsxException("Sample is too big: " + file.getAbsolutePath()); } } // Set member variables int frameLength = audioDataListChannel1.size() / 2; this.setNumberOfSampleFrames(frameLength); this.setEnd(frameLength - 1); this.setLoopStart(frameLength - 1); this.setSampleRate((int) audioFormatEncoded.getSampleRate()); this.setAudioDataChannel1(EsxUtil.listToByteArray(audioDataListChannel1)); this.setAudioDataChannel2(EsxUtil.listToByteArray(audioDataListChannel2)); this.setStereoOriginal(isAudioDataStereo); // Set calculated Sample Tune (from Sample Rate) SampleTune newSampleTune = EsxFactory.eINSTANCE.createSampleTune(); float newFloat = newSampleTune.calculateSampleTuneFromSampleRate(this.getSampleRate()); newSampleTune.setValue(newFloat); this.setSampleTune(newSampleTune); // Set name String newSampleName = new String(); newSampleName = StringUtils.left(StringUtils.trim(file.getName()), 8); this.setName(newSampleName); // Attempt to set loopStart and End from .wav smpl chunk if (file.getAbsolutePath().toLowerCase().endsWith(".wav")) { try { RIFFWave riffWave = WavFactory.eINSTANCE.createRIFFWave(file); ChunkSampler chunkSampler = (ChunkSampler) riffWave .getFirstChunkByEClass(WavPackage.Literals.CHUNK_SAMPLER); if (chunkSampler != null && chunkSampler.getSampleLoops().size() > 0) { SampleLoop sampleLoop = chunkSampler.getSampleLoops().get(0); Long tempLoopStart = sampleLoop.getStart(); Long tempLoopEnd = sampleLoop.getEnd(); if (tempLoopStart < this.getEnd() && tempLoopStart >= 0) { this.setLoopStart(tempLoopStart.intValue()); } if (tempLoopEnd < this.getEnd() && tempLoopEnd > this.getLoopStart()) { this.setEnd(tempLoopEnd.intValue()); } } } catch (Exception e) { e.printStackTrace(); } } } catch (UnsupportedAudioFileException e) { e.printStackTrace(); throw new EsxException("Invalid audio file: " + file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); throw new EsxException("Invalid audio file: " + file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); throw new EsxException("Invalid audio file: " + file.getAbsolutePath()); } }
From source file:net.sf.firemox.tools.MToolKit.java
/** * loadClip loads the sound-file into a clip. * // w ww . j av a 2s . co m * @param soundFile * file to be loaded and played. */ public static void loadClip(String soundFile) { AudioFormat audioFormat = null; AudioInputStream actionIS = null; try { // actionIS = AudioSystem.getAudioInputStream(input); // Does not work ! actionIS = AudioSystem.getAudioInputStream(MToolKit.getFile(MToolKit.getSoundFile(soundFile))); AudioFormat.Encoding targetEncoding = AudioFormat.Encoding.PCM_SIGNED; actionIS = AudioSystem.getAudioInputStream(targetEncoding, actionIS); audioFormat = actionIS.getFormat(); } catch (UnsupportedAudioFileException afex) { Log.error(afex); } catch (IOException ioe) { if (ioe.getMessage().equalsIgnoreCase("mark/reset not supported")) { // Ignore Log.error("IOException ignored."); } Log.error(ioe.getStackTrace()); } // define the required attributes for our line, // and make sure a compatible line is supported. // get the source data line for play back. DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); if (!AudioSystem.isLineSupported(info)) { Log.error("LineCtrl matching " + info + " not supported."); return; } // Open the source data line for play back. try { Clip clip = null; try { Clip.Info info2 = new Clip.Info(Clip.class, audioFormat); clip = (Clip) AudioSystem.getLine(info2); clip.open(actionIS); clip.start(); } catch (IOException ioe) { Log.error(ioe); } } catch (LineUnavailableException ex) { Log.error("Unable to open the line: " + ex); return; } }
From source file:com.opensmile.maven.EmoRecService.java
private double getAudioDuration(String filename) { File file = new File(filename); AudioInputStream audioInputStream; float durationInSeconds = 0; try {//from w ww. java 2s. c om audioInputStream = AudioSystem.getAudioInputStream(file); AudioFormat format = audioInputStream.getFormat(); long audioFileLength = file.length(); int frameSize = format.getFrameSize(); float frameRate = format.getFrameRate(); durationInSeconds = (audioFileLength / (frameSize * frameRate)); } catch (UnsupportedAudioFileException | IOException e) { e.printStackTrace(); } return durationInSeconds; }