我正在尝试使用sun.audio.Audiplayer和sun.audio.AudioStream的功能设计一个类。我希望能够使用声音文件的文件路径作为参数来实例化对象,然后只需调用一种方法来播放指定的文件。我拥有的代码可以运行,但是不能多次播放任何文件。我该如何解决?
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;
}
}
}
}
答案 0 :(得分:0)
流通常只能读取一次。因此,在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);
}
}
}
如果文件较小,则可以使用字节缓冲区将音频保留在内存中,但是如果文件较小,则将其存储在内存中的收益也很小。