我正在尝试使用sun.audio.Audiplayer和sun.audio.AudioStream的功能来设计一个类。我希望能够以soundfile的filepath作为参数实例化对象,然后简单地调用一个方法来播放指定的文件。我的代码可以工作,但不能播放任何文件超过一次。我该如何解决这个问题呢?
public class AudioFile {
// attributes
private AudioStream audioStream;
// constructors
public AudioFile(String filePath) throws FileNotFoundException, IOException { // improper exception-handling, to be fixed
// declare the file path to an FileInputStream
InputStream inputStream = new FileInputStream(filePath);
// create an AudioStream from the InputStream
AudioStream audioStream = new AudioStream(inputStream);
this.audioStream = audioStream;
}
// methods
public void playFile() {
// start playing sound file
AudioPlayer.player.start(audioStream);
}
public class Main {
public static void main(String[] args) throws IOException, InterruptedException { // improper exception-handling, to be fixed
// instantiate new AudioFile objects with path to sound files
AudioFile correctSound = new AudioFile("sfx/correct.wav");
AudioFile boingSound = new AudioFile("sfx/boing.wav");
Scanner scanner = new Scanner(System.in);
while(true) {
int input = scanner.nextInt();
switch (input) {
case 1:
correctSound.playFile();
System.out.println("Correct!");
break;
case 2:
boingSound.playFile();
System.out.println("Boing!");
break;
}
}
}
}发布于 2018-11-16 01:30:18
流一般只能读取一次。因此,在AudioStream使用了流之后,它就不能再使用了。
一个简单的实现可能如下所示:每次播放音频时创建并打开一个流。
public class AudioFile {
// attributes
private String filePath;
// constructors
public AudioFile(String filePath) { // improper exception-handling, to be fixed
// declare the file path to an FileInputStream
this.filePath=filePath;
}
// methods
public void playFile() throws FileNotFoundException, IOException {
// Put open of FileInputStream in a try to be sure to close it
try(InputStream inputStream = new FileInputStream(filePath)){
// create an AudioStream from the InputStream
AudioStream audioStream = new AudioStream(inputStream);
this.audioStream = audioStream;
// start playing sound file
AudioPlayer.player.start(audioStream);
}
}
}如果文件很小,则可以使用字节缓冲区将音频保存在内存中,但如果文件很小,则将其存储在内存中也没有什么好处。
https://stackoverflow.com/questions/53322262
复制相似问题