2

我有一个非常简单的类,可以使用以下代码播放声音文件:

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();

}

}

但是,当我创建此类的一个实例并在其上调用播放函数时,我没有听到任何声音。当声音开始和结束时,我听到砰砰声,但不是实际文件。我也没有得到任何类型的错误。

我究竟做错了什么?

4

3 回答 3

1

使用它并注意这不是我的代码,它来自这里: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();
}

我希望这有帮助。

于 2014-06-25T14:54:27.063 回答
0

尝试类似:

File soundFile = new File( "something.wav" );
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( soundFile );
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();//This plays the audio

您可能必须AudioSystem.getClip() 加载音频流后使用。

于 2014-06-25T08:55:56.940 回答
0

根据我的经验,音频文件使用频繁的罪魁祸首。显然,Java 不能播放压缩的声音文件或类似的东西。它只播放线性 PCM 文件。我可能是错的唯一。有人有播放任何类型声音文件的示例吗?

于 2014-12-03T17:37:04.460 回答