List of usage examples for javax.sound.sampled AudioSystem getAudioInputStream
public static AudioInputStream getAudioInputStream(final File file) throws UnsupportedAudioFileException, IOException
From source file:Main.java
/** Read sampled audio data from the specified URL and play it */ public static void streamSampledAudio(URL url) throws IOException, UnsupportedAudioFileException, LineUnavailableException { AudioInputStream ain = null; // We read audio data from here SourceDataLine line = null; // And write it here. try {/* ww w . j av a2 s .c o m*/ // Get an audio input stream from the URL ain = AudioSystem.getAudioInputStream(url); // Get information about the format of the stream AudioFormat format = ain.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); // If the format is not supported directly (i.e. if it is not PCM // encoded, then try to transcode it to PCM. if (!AudioSystem.isLineSupported(info)) { // This is the PCM format we want to transcode to. // The parameters here are audio format details that you // shouldn't need to understand for casual use. AudioFormat pcm = new AudioFormat(format.getSampleRate(), 16, format.getChannels(), true, false); // Get a wrapper stream around the input stream that does the // transcoding for us. ain = AudioSystem.getAudioInputStream(pcm, ain); // Update the format and info variables for the transcoded data format = ain.getFormat(); info = new DataLine.Info(SourceDataLine.class, format); } // Open the line through which we'll play the streaming audio. line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); // Allocate a buffer for reading from the input stream and writing // to the line. Make it large enough to hold 4k audio frames. // Note that the SourceDataLine also has its own internal buffer. int framesize = format.getFrameSize(); byte[] buffer = new byte[4 * 1024 * framesize]; // the buffer int numbytes = 0; // how many bytes // We haven't started the line yet. boolean started = false; for (;;) { // We'll exit the loop when we reach the end of stream // First, read some bytes from the input stream. int bytesread = ain.read(buffer, numbytes, buffer.length - numbytes); // If there were no more bytes to read, we're done. if (bytesread == -1) break; numbytes += bytesread; // Now that we've got some audio data, to write to the line, // start the line, so it will play that data as we write it. if (!started) { line.start(); started = true; } // We must write bytes to the line in an integer multiple of // the framesize. So figure out how many bytes we'll write. int bytestowrite = (numbytes / framesize) * framesize; // Now write the bytes. The line will buffer them and play // them. This call will block until all bytes are written. line.write(buffer, 0, bytestowrite); // If we didn't have an integer multiple of the frame size, // then copy the remaining bytes to the start of the buffer. int remaining = numbytes - bytestowrite; if (remaining > 0) System.arraycopy(buffer, bytestowrite, buffer, 0, remaining); numbytes = remaining; } // Now block until all buffered sound finishes playing. line.drain(); } finally { // Always relinquish the resources we use if (line != null) line.close(); if (ain != null) ain.close(); } }
From source file:org.snitko.app.playback.PlaySound.java
public void play(File inputFile) { try (final AudioInputStream in = AudioSystem.getAudioInputStream(inputFile)) { final AudioFormat outFormat = getOutFormat(in.getFormat()); final DataLine.Info info = new DataLine.Info(SourceDataLine.class, outFormat); try (final SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info)) { if (sourceDataLine != null) { sourceDataLine.open(outFormat); sourceDataLine.start();//from ww w. j a v a2 s . c om AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(outFormat, in); stream(audioInputStream, sourceDataLine); sourceDataLine.drain(); sourceDataLine.stop(); } } } catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) { throw new IllegalStateException(e); } }
From source file:org.openhab.io.multimedia.actions.Audio.java
@ActionDoc(text = "plays a sound from the sounds folder") static public void playSound( @ParamDoc(name = "filename", text = "the filename with extension") String filename) { try {/* ww w .ja v a 2 s. c o m*/ InputStream is = new FileInputStream(SOUND_DIR + File.separator + filename); if (filename.toLowerCase().endsWith(".mp3")) { Player player = new Player(is); playInThread(player); } else { AudioInputStream ais = AudioSystem.getAudioInputStream(is); Clip clip = AudioSystem.getClip(); clip.open(ais); playInThread(clip); } } catch (FileNotFoundException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (JavaLayerException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (UnsupportedAudioFileException e) { logger.error("Format of sound file '{}' is not supported: {}", new String[] { filename, e.getMessage() }); } catch (IOException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } catch (LineUnavailableException e) { logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() }); } }
From source file:com.jostrobin.battleships.view.sound.DefaultSoundEffects.java
private void playSound(final String path) { if (enabled) { InputStream is = ClassLoader.getSystemResourceAsStream(path); AudioInputStream audioInputStream = null; try {/*from w ww .j a va2s .c om*/ audioInputStream = AudioSystem.getAudioInputStream(is); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); while (clip.isRunning()) { Thread.sleep(10); } } catch (Exception e) { logger.warn("Could not play sound effect", e); } finally { IOUtils.closeSilently(is, audioInputStream); } } }
From source file:com.lfv.lanzius.application.SoundClip.java
public SoundClip(Mixer outputMixer, String filenameAlternativeA, String filenameAlternativeB, int periodMillis, float volumeAdjustment) { log = LogFactory.getLog(getClass()); if (soundTimer == null) soundTimer = new Timer("Ssoundclip", true); boolean altA = true; this.periodMillis = periodMillis; this.volumeAdjustment = volumeAdjustment; // Try to open the first alternative clip try {// ww w .java 2 s . c om stream = AudioSystem.getAudioInputStream(new File(filenameAlternativeA)); DataLine.Info dataLineInfo = new DataLine.Info(Clip.class, stream.getFormat()); clip = (Clip) outputMixer.getLine(dataLineInfo); clip.open(stream); } catch (Exception ex) { // The first alternative clip could not be opened, try with second alternative try { if (stream != null) stream.close(); if (filenameAlternativeB == null) throw ex; stream = AudioSystem.getAudioInputStream(new File(filenameAlternativeB)); DataLine.Info dataLineInfo = new DataLine.Info(Clip.class, stream.getFormat()); clip = (Clip) outputMixer.getLine(dataLineInfo); clip.open(stream); altA = false; } catch (Exception ex2) { log.error("Unable to get stream for file " + filenameAlternativeA); log.error("Unable to get stream for file " + filenameAlternativeB); if (stream != null) { try { stream.close(); } catch (IOException ex3) { log.error("Error closing stream ", ex3); } } stream = null; return; } } int clipLength = (int) (clip.getMicrosecondLength() / 1000L); log.debug("Loading sound clip " + (altA ? filenameAlternativeA : filenameAlternativeB) + " (" + clipLength + "ms)"); // Check length if (periodMillis < clipLength) throw new IllegalArgumentException("The periodMillis value must be larger than length of the clip"); }
From source file:patientview.HistoryJFrame.java
/** * Creates new form HistoryJFrame//from w w w .ja va 2s.com */ public HistoryJFrame(int bedNum, int time, Patients patients) { initComponents(); //set window in the center of the screen //Get the size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); //Determine the new location of the window int w = this.getSize().width; int h = this.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; //Move the window this.setLocation(x, y); //Load click sound try { AudioInputStream audioInputStream = AudioSystem .getAudioInputStream(new File("sounds/click.wav").getAbsoluteFile()); click = AudioSystem.getClip(); click.open(audioInputStream); } catch (Exception ex) { System.out.println(ex.toString()); } //Get patient this.patients = patients; this.bedNum = bedNum; thisPatient = patients.getPatient(bedNum); //Set background colour this.getContentPane().setBackground(new Color(240, 240, 240)); //fill titles wardNumField.setText("W001"); bedNumField.setText(String.valueOf(bedNum)); checkBoxes = new ArrayList<JCheckBox>() { { add(jCheckBox1); add(jCheckBox2); add(jCheckBox3); add(jCheckBox4); add(jCheckBox5); add(jCheckBox6); } }; genGraph(getGraphCode()); //set timer timerCSeconds = time; if (timer == null) { timer = new Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do it every 10 msecond Calendar cal = Calendar.getInstance(); cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); jLabel_systemTime.setText(sdf.format(cal.getTime())); // do it every 5 seconds if (timerCSeconds % 500 == 0) { //genGraph(getGraphCode()); //only useful for dispalying data up until the current moment } timerCSeconds++; } }); } if (timer.isRunning() == false) { timer.start(); } }
From source file:de.tor.tribes.util.ClipboardWatch.java
private synchronized void playNotification() { if (!Boolean.parseBoolean(GlobalOptions.getProperty("clipboard.notification"))) { return;/*from www .j a v a2s. co m*/ } Timer t = new Timer("ClipboardNotification", true); t.schedule(new TimerTask() { @Override public void run() { if (clip != null) {//reset clip clip.stop(); clip.setMicrosecondPosition(0); } if (ac != null) { ac.stop(); } try { if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) { if (clip == null) { clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem .getAudioInputStream(ClockFrame.class.getResourceAsStream("/res/Ding.wav")); clip.open(inputStream); } clip.start(); } else { if (ac == null) { ac = Applet.newAudioClip(ClockFrame.class.getResource("/res/Ding.wav")); } ac.play(); } } catch (Exception e) { logger.error("Failed to play notification", e); } } }, 0); }
From source file:marytts.tests.junit4.EnvironmentTest.java
@Test public void testMP3Available() throws Exception { AudioFormat mp3af = new AudioFormat(new AudioFormat.Encoding("MPEG1L3"), AudioSystem.NOT_SPECIFIED, AudioSystem.NOT_SPECIFIED, 1, AudioSystem.NOT_SPECIFIED, AudioSystem.NOT_SPECIFIED, false); AudioInputStream waveStream = AudioSystem .getAudioInputStream(this.getClass().getResourceAsStream("test.wav")); // Now attempt conversion: if (MaryRuntimeUtils.canCreateMP3()) { assertTrue(AudioSystem.isConversionSupported(mp3af, waveStream.getFormat())); AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(mp3af, waveStream); } else {//from ww w. j a va 2 s . c o m assertFalse(AudioSystem.isConversionSupported(mp3af, waveStream.getFormat())); } }
From source file:com.gameminers.mav.audio.AudioManager.java
public void playClip(String key) { if (!clips.containsKey(key)) throw new RuntimeException("No clip with key '" + key + "'"); try {//w w w . j a v a2s .c o m sink.setAudioInputStream(AudioSystem.getAudioInputStream(new ByteArrayInputStream(clips.get(key)))); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:it.sardegnaricerche.voiceid.sr.VCluster.java
public void trimSegments(File inputFile) throws IOException { String base = Utils.getBasename(inputFile); File mydir = new File(base); mydir.mkdirs();//w ww. j a v a 2s. c o m String mywav = mydir.getAbsolutePath() + "/" + this.getLabel() + ".wav"; AudioFileFormat fileFormat = null; AudioInputStream inputStream = null; AudioInputStream shortenedStream = null; AudioInputStream current = null; int bytesPerSecond = 0; long framesOfAudioToCopy = 0; wavFile = new File(mywav); try { fileFormat = AudioSystem.getAudioFileFormat(inputFile); AudioFormat format = fileFormat.getFormat(); boolean firstTime = true; for (VSegment s : this.getSegments()) { bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate(); inputStream = AudioSystem.getAudioInputStream(inputFile); inputStream.skip(0); inputStream.skip((int) (s.getStart() * 100) * bytesPerSecond / 100); framesOfAudioToCopy = (int) (s.getDuration() * 100) * (int) format.getFrameRate() / 100; if (firstTime) { shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy); } else { current = new AudioInputStream(inputStream, format, framesOfAudioToCopy); shortenedStream = new AudioInputStream(new SequenceInputStream(shortenedStream, current), format, shortenedStream.getFrameLength() + framesOfAudioToCopy); } firstTime = false; } AudioSystem.write(shortenedStream, fileFormat.getType(), wavFile); } catch (Exception e) { logger.severe(e.getMessage()); e.printStackTrace(); } finally { if (inputStream != null) try { inputStream.close(); } catch (Exception e) { logger.severe(e.getMessage()); } if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { logger.severe(e.getMessage()); } if (current != null) try { current.close(); } catch (Exception e) { logger.severe(e.getMessage()); } } logger.fine("filename: " + wavFile.getAbsolutePath()); }