You can the
javax.sound.sampled
package to do that!
If you create a class
SoundPlayer looking something like this;
package com.bornander.soundexample;
import java.io.File;
import java.io.FileFilter;
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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class SoundPlayer {
private static final int BUFFER_SIZE = 1024 * 1024;
public static void playDirectory(final String directory, final FileFilter filter) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
final File directoryInfo = new File(directory);
if (directoryInfo.exists() && directoryInfo.isDirectory()) {
for(File file : directoryInfo.listFiles(filter)) {
playFile(file);
}
}
}
public static void playFile(final File file) throws UnsupportedAudioFileException, IOException, LineUnavailableException{
AudioInputStream audioStream = null;
SourceDataLine sourceLine = null;
try {
audioStream = AudioSystem.getAudioInputStream(file);
final AudioFormat audioFormat = audioStream.getFormat();
final DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
sourceLine.start();
int bytesRead = 0;
final byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead= audioStream.read(buffer, 0, buffer .length)) != -1) {
if (bytesRead>= 0) {
sourceLine.write(buffer, 0, bytesRead);
}
}
}
finally {
if (audioStream != null)
audioStream.close();
if (sourceLine != null) {
sourceLine.drain();
sourceLine.close();
}
}
}
}
Then you can play individual files using the
playFile
method, or all files in a directory using the
playDirectory
method.
Like this;
package com.bornander.soundexample;
import java.io.File;
import java.io.FileFilter;
public class Program {
public static void main(String[] args) throws Exception {
SoundPlayer.playDirectory("C:\\Users\\Fredrik\\Sounds", new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".wav");
}
});
}
}
Hope this helps,
Fredrik