我有一个非常简单的类,可以使用以下代码播放声音文件:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sound{
private Clip sound;
public Sound(String location){
try{
sound = AudioSystem.getClip();
File file = new File(location);
sound.open(AudioSystem.getAudioInputStream(file));
}
catch(IOException | LineUnavailableException | UnsupportedAudioFileException error){
System.out.println(error);
}
}
public void play(){
sound.start();
}
}
但是,当我创建此类的实例并调用其播放函数时,我没有听到任何声音。当声音开始和结束时我听到爆裂声,但不是实际的文件。我也没有收到任何类型的错误。
我究竟做错了什么?
使用这个并注意这不是我的代码,它来自这里:如何用java播放.wav文件 https://stackoverflow.com/questions/2416935/how-to-play-wav-files-with-java我唯一做的就是将其发布在这里并对其进行一些优化。
private final int BUFFER_SIZE = 128000;
private AudioInputStream audioStream;
private SourceDataLine sourceLine;
/**
* @param filename the name of the file that is going to be played
*/
public void playSound(String filename){
try {
audioStream = AudioSystem.getAudioInputStream(new File(filename));
} catch (Exception e){
e.printStackTrace();
}
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioStream.getFormat()));
sourceLine.open(audioStream.getFormat());
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
sourceLine.start();
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) {
@SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
我希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)