List of usage examples for javax.sound.sampled AudioSystem getLine
public static Line getLine(Line.Info info) throws LineUnavailableException
From source file:CoreJavaSound.java
public CoreJavaSound() throws Exception { JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null);//from w ww. ja v a 2 s. c o m soundFile = chooser.getSelectedFile(); System.out.println("Playing " + soundFile.getName()); Line.Info linfo = new Line.Info(Clip.class); Line line = AudioSystem.getLine(linfo); clip = (Clip) line; clip.addLineListener(this); AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); clip.open(ais); clip.start(); }
From source file:Main.java
public void playSound(final String filename) throws Exception { InputStream audioSrc = this.getClass().getResourceAsStream(filename); InputStream bufferedIn = new BufferedInputStream(audioSrc); audioStream = AudioSystem.getAudioInputStream(bufferedIn); audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat);/*from ww w.j av a 2 s .c om*/ sourceLine.start(); running = true; while (running) { audioStream.mark(BUFFER_SIZE); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { sourceLine.write(abData, 0, nBytesRead); } } if (running) audioStream.reset(); } sourceLine.drain(); sourceLine.close(); }
From source file:Main.java
public Main() throws Exception { URL imageURL = getClass().getClassLoader().getResource("images/k.jpeg"); buttonIcon = new ImageIcon(imageURL); button = new JButton("Click to Buh!", buttonIcon); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (buhClip != null) { buhClip.setFramePosition(0); buhClip.start();/* w ww. j a v a 2s . com*/ } else System.out.println("Couldn't load sound"); } }); getContentPane().add(button); URL soundURL = getClass().getClassLoader().getResource("sounds/b.aiff"); Line.Info linfo = new Line.Info(Clip.class); Line line = AudioSystem.getLine(linfo); buhClip = (Clip) line; AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL); buhClip.open(ais); }
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 {//from ww w .j a va2 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:fr.ritaly.dungeonmaster.audio.SoundSystemV1.java
public void play(Position position, final AudioClip clip) { if (position == null) { throw new IllegalArgumentException("The given position is null"); }//w ww . j a v a 2s. c o m if (clip == null) { throw new IllegalArgumentException("The given audio clip is null"); } if (!isInitialized()) { return; } if (log.isDebugEnabled()) { log.debug("Submitting new task ..."); } executorService.execute(new Runnable() { @Override public void run() { final Sound sound = sounds.get(clip.getSound()); if (sound == null) { throw new IllegalArgumentException("Unsupported sound <" + clip + ">"); } final DataLine.Info info = new DataLine.Info(SourceDataLine.class, sound.getAudioFormat()); try { final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(sound.getAudioFormat()); line.start(); line.write(sound.getData(), 0, sound.getData().length); line.drain(); line.close(); } catch (LineUnavailableException e) { throw new RuntimeException(e); } } }); if (log.isDebugEnabled()) { log.debug("Task submitted"); } // TODO Calculer distance, pan, attnuation ... }
From source file:SimpleSoundPlayer.java
public boolean loadSound(Object object) { duration = 0.0;//from w ww. jav a2 s .co m currentName = ((File) object).getName(); try { currentSound = AudioSystem.getAudioInputStream((File) object); } catch (Exception e1) { try { FileInputStream is = new FileInputStream((File) object); currentSound = new BufferedInputStream(is, 1024); } catch (Exception e3) { e3.printStackTrace(); currentSound = null; return false; } // } } // user pressed stop or changed tabs while loading if (sequencer == null) { currentSound = null; return false; } if (currentSound instanceof AudioInputStream) { try { AudioInputStream stream = (AudioInputStream) currentSound; AudioFormat format = stream.getFormat(); /** * we can't yet open the device for ALAW/ULAW playback, convert * ALAW/ULAW to PCM */ if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW)) { AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); stream = AudioSystem.getAudioInputStream(tmp, stream); format = tmp; } DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); Clip clip = (Clip) AudioSystem.getLine(info); clip.addLineListener(this); clip.open(stream); currentSound = clip; // seekSlider.setMaximum((int) stream.getFrameLength()); } catch (Exception ex) { ex.printStackTrace(); currentSound = null; return false; } } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) { try { sequencer.open(); if (currentSound instanceof Sequence) { sequencer.setSequence((Sequence) currentSound); } else { sequencer.setSequence((BufferedInputStream) currentSound); } } catch (InvalidMidiDataException imde) { System.out.println("Unsupported audio file."); currentSound = null; return false; } catch (Exception ex) { ex.printStackTrace(); currentSound = null; return false; } } duration = getDuration(); return true; }
From source file:SoundPlayer.java
public SoundPlayer(File f, boolean isMidi) throws IOException, UnsupportedAudioFileException, LineUnavailableException, MidiUnavailableException, InvalidMidiDataException { if (isMidi) { // The file is a MIDI file midi = true;//from ww w .j av a 2s .c om // First, get a Sequencer to play sequences of MIDI events // That is, to send events to a Synthesizer at the right time. sequencer = MidiSystem.getSequencer(); // Used to play sequences sequencer.open(); // Turn it on. // Get a Synthesizer for the Sequencer to send notes to Synthesizer synth = MidiSystem.getSynthesizer(); synth.open(); // acquire whatever resources it needs // The Sequencer obtained above may be connected to a Synthesizer // by default, or it may not. Therefore, we explicitly connect it. Transmitter transmitter = sequencer.getTransmitter(); Receiver receiver = synth.getReceiver(); transmitter.setReceiver(receiver); // Read the sequence from the file and tell the sequencer about it sequence = MidiSystem.getSequence(f); sequencer.setSequence(sequence); audioLength = (int) sequence.getTickLength(); // Get sequence length } else { // The file is sampled audio midi = false; // Getting a Clip object for a file of sampled audio data is kind // of cumbersome. The following lines do what we need. AudioInputStream ain = AudioSystem.getAudioInputStream(f); try { DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat()); clip = (Clip) AudioSystem.getLine(info); clip.open(ain); } finally { // We're done with the input stream. ain.close(); } // Get the clip length in microseconds and convert to milliseconds audioLength = (int) (clip.getMicrosecondLength() / 1000); } // Now create the basic GUI play = new JButton("Play"); // Play/stop button progress = new JSlider(0, audioLength, 0); // Shows position in sound time = new JLabel("0"); // Shows position as a # // When clicked, start or stop playing the sound play.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (playing) stop(); else play(); } }); // Whenever the slider value changes, first update the time label. // Next, if we're not already at the new position, skip to it. progress.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { int value = progress.getValue(); // Update the time label if (midi) time.setText(value + ""); else time.setText(value / 1000 + "." + (value % 1000) / 100); // If we're not already there, skip there. if (value != audioPosition) skip(value); } }); // This timer calls the tick() method 10 times a second to keep // our slider in sync with the music. timer = new javax.swing.Timer(100, new ActionListener() { public void actionPerformed(ActionEvent e) { tick(); } }); // put those controls in a row Box row = Box.createHorizontalBox(); row.add(play); row.add(progress); row.add(time); // And add them to this component. setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(row); // Now add additional controls based on the type of the sound if (midi) addMidiControls(); else addSampledControls(); }
From source file:fr.ritaly.dungeonmaster.audio.SoundSystem.java
private void play(final double angle, final double distance, final AudioClip clip) { if (clip == null) { throw new IllegalArgumentException("The given audio clip is null"); }/*w ww .j a v a 2 s.co m*/ if (!isInitialized()) { // On ne lve pas d'erreur pour les tests unitaires return; } if (log.isDebugEnabled()) { log.debug("Submitting new task ..."); } executorService.execute(new Runnable() { @Override public void run() { final Sound sound = sounds.get(clip.getSound()); if (sound == null) { throw new IllegalArgumentException("Unsupported sound <" + clip + ">"); } try { final Clip clip2 = (Clip) AudioSystem .getLine(new DataLine.Info(Clip.class, sound.getAudioFormat())); clip2.addLineListener(new LineListener() { @Override public void update(LineEvent event) { if (event.getType().equals(LineEvent.Type.STOP)) { clip2.close(); } } }); clip2.open(sound.getAudioFormat(), sound.getData(), 0, sound.getData().length); final DecimalFormat decimalFormat = new DecimalFormat("###.#"); // Pan dans [-1, +1] final FloatControl pan = (FloatControl) clip2.getControl(FloatControl.Type.PAN); if (!Double.isNaN(angle)) { final float p = (float) Math.sin(angle); if ((0 <= angle) && (angle <= Math.PI)) { // Son sur la gauche, pan positif pan.setValue(p); } else { // Son sur la droite, pan ngatif pan.setValue(p); } if (log.isDebugEnabled()) { log.debug("Angle = " + decimalFormat.format((angle / Math.PI) * 180) + " / Pan = " + decimalFormat.format(p * 100)); } } else { pan.setValue(0); } final double attenuation = Utils.attenuation(distance); if (log.isDebugEnabled()) { log.debug("Distance = " + distance + " / Attenuation = " + decimalFormat.format((attenuation * 100)) + "%"); } if (distance != 0) { // Gain dans [-30, 0] final FloatControl gain = (FloatControl) clip2.getControl(FloatControl.Type.MASTER_GAIN); gain.setValue((float) attenuation * -30); } clip2.loop(0); } catch (LineUnavailableException e) { throw new RuntimeException(e); } } }); if (log.isDebugEnabled()) { log.debug("Task submitted"); } }
From source file:edu.tsinghua.lumaqq.Sounder.java
/** * /*from www.j a va 2s . c o m*/ * @param filename * @return */ private boolean loadSound(String filename) { // ?? File file = new File(filename); try { currentSound = AudioSystem.getAudioInputStream(file); } catch (Exception e) { try { FileInputStream is = new FileInputStream(file); currentSound = new BufferedInputStream(is, 1024); } catch (Exception ex) { log.error(ex.getMessage()); currentSound = null; return false; } } // ?????? if (currentSound instanceof AudioInputStream) { try { AudioInputStream stream = (AudioInputStream) currentSound; AudioFormat format = stream.getFormat(); // ?? ALAW/ULAW ? ALAW/ULAW ?? PCM if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW)) { AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); stream = AudioSystem.getAudioInputStream(tmp, stream); format = tmp; } DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(stream); currentSound = clip; } catch (Exception ex) { log.error(ex.getMessage()); currentSound = null; return false; } } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) { try { sequencer.open(); if (currentSound instanceof Sequence) { sequencer.setSequence((Sequence) currentSound); } else { sequencer.setSequence((BufferedInputStream) currentSound); } log.trace("Sequence Created"); } catch (InvalidMidiDataException imde) { log.error("???"); currentSound = null; return false; } catch (Exception ex) { log.error(ex.getMessage()); currentSound = null; return false; } } return true; }
From source file:Filter3dTest.java
/** * Plays a stream. This method blocks (doesn't return) until the sound is * finished playing.//from w w w .j a v a 2 s.c om */ public void play(InputStream source) { // use a short, 100ms (1/10th sec) buffer for real-time // change to the sound stream int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; // create a line to play to SourceDataLine line; try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, bufferSize); } catch (LineUnavailableException ex) { ex.printStackTrace(); return; } // start the line line.start(); // copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { ex.printStackTrace(); } // wait until all data is played, then close the line line.drain(); line.close(); }