Question:
How do you play .Wav files in java?
Hawkeh
2010-11-30 14:40:22 UTC
I've found a lot of examples but none work. I'm using BlueJ. I am relatively new to Java and I need to learn how to add sound for our ShowCase Project.
Four answers:
Jared
2010-11-30 15:43:56 UTC
The Java Sound library can be VERY hard to penetrate (I have found). But playing audio should be very simple.



First you need to realize that the static class AudioSystem is used as an entry point to your sound card (essentially). You need to get all your lines from AudioSystem.



For playback the goal is to write data to the output (your speakers). Therefore you want to WRITE to something. The type of line you need is therefore is SourceDataLine. The way you use a source data line is by writing bytes to it...so what in the heck does that mean??



Well what you write depends on A LOT of things...but basically it depends on the data format, i.e. linear pcm, dolby digital, mp3, .wav (which incidentally is essentially encoded in linear pcm), etc.



So how will you know what to write to your source data line?? That's easy, you want to read from a file that has the bytes in it (the .wav file). Luckily there is a way to get an input stream from a file:



AudioSystem.getAudioInputStream(...):

http://download.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioSystem.html#getAudioInputStream%28java.io.File%29



So NOW you need to understand how the AudioInputStream works. You can read bytes (that can be put into a source data line for playback) from the AudioInputStream with any of the read(...) methods:



http://download.oracle.com/javase/6/docs/api/javax/sound/sampled/AudioInputStream.html#read%28%29



The best way is going to be to read lots of data at a time. So you usually choose a default buffer size. Then you can read the bytes into an array from the input stream. Then write those bytes to a source data line:



Putting ALL of that together you can get a fairly simple main method (you'll have to import the sound package: javax.sound.sampled.*;)



public static final int BUFF_SIZE = 1024;



public static final String fileName = "fileName.wav";

public static final File wavFile = new File(fileName);

public static final byte[] BUFFER = new byte[BUFF_SIZE];



public static void main(String...args){

AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);

SourceDataLine sdl = AudioSystem.getSourceDataLine(ais.getFormat());

int bytesRead;



sdl.open();

sdl.start();//start playing whatever is in this source data line



//read until ais.read(...) returns -1 (meaning no bytes were read)

while((bytesRead = ais.read(BUFFER)) >= 0){

sdl.write(BUFFER, 0, bytesRead);//write the contents of BUFFER into source data line

}



sdl.flush();//make sure you play the rest of the file (if the above loop finishes before playback)

}



That should do it. Notice that you have to do a little bit extra to actually start playing the file:



sdl.open(): This makes the line "operational"...whatever that means, but you need it

sdl.start(): This makes the line able to start acquiring data...if you left this out all of the writes would have no affect.



So the prescription is to get an AudioInputStream then write that stream (through an intermediate buffer) to a source data line.





}
2010-11-30 14:44:17 UTC
import java.io.File;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.FloatControl;

import javax.sound.sampled.LineUnavailableException;

import javax.sound.sampled.SourceDataLine;

import javax.sound.sampled.UnsupportedAudioFileException;



public class AePlayWave extends Thread {



private String filename;



private Position curPosition;



private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb



enum Position {

LEFT, RIGHT, NORMAL

};



public AePlayWave(String wavfile) {

filename = wavfile;

curPosition = Position.NORMAL;

}



public AePlayWave(String wavfile, Position p) {

filename = wavfile;

curPosition = p;

}



public void run() {



File soundFile = new File(filename);

if (!soundFile.exists()) {

System.err.println("Wave file not found: " + filename);

return;

}



AudioInputStream audioInputStream = null;

try {

audioInputStream = AudioSystem.getAudioInputStream(soundFile);

} catch (UnsupportedAudioFileException e1) {

e1.printStackTrace();

return;

} catch (IOException e1) {

e1.printStackTrace();

return;

}



AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);



try {

auline = (SourceDataLine) AudioSystem.getLine(info);

auline.open(format);

} catch (LineUnavailableException e) {

e.printStackTrace();

return;

} catch (Exception e) {

e.printStackTrace();

return;

}



if (auline.isControlSupported(FloatControl.Type.PAN)) {

FloatControl pan = (FloatControl) auline

.getControl(FloatControl.Type.PAN);

if (curPosition == Position.RIGHT)

pan.setValue(1.0f);

else if (curPosition == Position.LEFT)

pan.setValue(-1.0f);

}



auline.start();

int nBytesRead = 0;

byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];



try {

while (nBytesRead != -1) {

nBytesRead = audioInputStream.read(abData, 0, abData.length);

if (nBytesRead >= 0)

auline.write(abData, 0, nBytesRead);

}

} catch (IOException e) {

e.printStackTrace();

return;

} finally {

auline.drain();

auline.close();

}



}

}
2010-11-30 20:03:07 UTC
Here is a somewhat...simpler method of playback, although I don't think there is much more you can do other than play the music, loop the music (play over and over), and stop the music, but here:



P.S. Don't let the URL and applet fool you, this program below is made to run offline



import java.net.URL;

import java.applet.*;



public class SoundEx extends JFrame implements ActionListener {



private AudioClip sound;

private URL urlForTheSound;



private JButton button1;



public SoundEx() {



this.urlForTheSound = SoundEx.class.getResource(*Insert the path to the sound file here*);

this.sound = Applet.newAudioClip(this.urlForTheSound);



this.setSize(200, 100);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setLocationRelativeTo(null);



this.button1 = new JButton("Press Me!");

this.button1.addActionListener(this);



JPanel panel1 = new JPanel();



panel1.add(this.button1);

this.add(panel1);



}



public void actionPerformed(ActionEvent e) {

sound.play();

}

}



//Note that you can also manipulate your AudioClip object to loop (sound.loop()) or stop (sound.stop())
2016-02-28 04:01:42 UTC
Like the error message said , no codec. It's sort of like a definition thing... Try VLC media player. I'm sure it will work.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...