首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sun.audio.AudioPlayer,AudioStream不会多次播放同一个声音文件

sun.audio.AudioPlayer,AudioStream不会多次播放同一个声音文件
EN

Stack Overflow用户
提问于 2018-11-15 23:01:28
回答 1查看 27关注 0票数 0

我正在尝试使用sun.audio.Audiplayer和sun.audio.AudioStream的功能来设计一个类。我希望能够以soundfile的filepath作为参数实例化对象,然后简单地调用一个方法来播放指定的文件。我的代码可以工作,但不能播放任何文件超过一次。我该如何解决这个问题呢?

代码语言:javascript
复制
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;
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-11-16 01:30:18

流一般只能读取一次。因此,在AudioStream使用了流之后,它就不能再使用了。

一个简单的实现可能如下所示:每次播放音频时创建并打开一个流。

代码语言:javascript
复制
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);
        }
    }
}

如果文件很小,则可以使用字节缓冲区将音频保存在内存中,但如果文件很小,则将其存储在内存中也没有什么好处。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53322262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档