你必須使用外部庫播放文件,如MP3播放
Java支持的唯一的.wav
但是這enough.All你需要的是一個外部算法播放多種音樂格式。所有其他格式來自.wav他們傳入算法,然後繁榮他們成爲.ogg,.mp3,.whatever
1.一個非常令人印象深刻的庫使用哪些支持.mp3 JLayer.jar 您可以將此jar作爲外部庫導入到您的項目中。
2.如果你搜索更多,你會發現JAudiotagger這只是驚人的,但很難使用。
3.您也可以使用Java Media FrameWork,但無論它支持多種格式。
4.JavaZoom也已經和其他庫來支持.OGG,.speex,.FLAC,MP3播放
鏈接的StackOverflow上How to play .wav files with java
而且http://alvinalexander.com/java/java-audio-example-java-au-play-sound 不知道這仍然工作java的8
此:
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.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioPlayerExample1 implements LineListener {
/**
* this flag indicates whether the playback completes or not.
*/
boolean playCompleted;
/**
* Play a given audio file.
* @param audioFilePath Path of the audio file.
*/
void play() {
File audioFile = new File("C:/Users/Alex.hp/Desktop/Musc/audio.wav");
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();
while (!playCompleted) {
// wait for the playback completes
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
audioClip.close();
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
/**
* Listens to the START and STOP events of the audio line.
*/
@Override
public void update(LineEvent event) {
LineEvent.Type type = event.getType();
if (type == LineEvent.Type.START) {
System.out.println("Playback started.");
} else if (type == LineEvent.Type.STOP) {
playCompleted = true;
System.out.println("Playback completed.");
}
}
public static void main(String[] args) {
AudioPlayerExample1 player = new AudioPlayerExample1();
player.play();
}
}
可能重複的[解決方法爲UnsupportedAudioFileException?](http://stackoverflow.com/questions/2843847/workaround-for-unsupportedaudiofileexception) – 2015-02-17 20:58:34
你想玩什麼文件? Java只支持.wav – crAlexander 2015-02-17 21:12:34
它試圖播放一個。wav文件 – Suji 2015-02-17 21:16:39