学习java。音频控制问题

时间:2011-08-26 20:59:08

标签: java audio

我是java的新手并试图为我的应用程序添加声音。我遇到的问题是音乐开始但是当第二次调用音乐方法时它不会停止。我做错了什么?

import sun.audio.*;
import java.io.*;

public class sound {
    private static boolean playing = false; 

    @SuppressWarnings("restriction")
    public static void music() {        
        try  {
            // open the sound file as a Java input stream
            String soundFile = "backgroundmusic.wav";
            InputStream in = new FileInputStream(soundFile);

            // create an audiostream from the inputstream
            AudioStream audioStream = new AudioStream(in);

            // play the audio clip with the audioplayer class
            if(playing == false){
                AudioPlayer.player.start(audioStream);
                playing = true;
            }else{
                AudioPlayer.player.stop(audioStream);
                playing = false;
            }
        } catch(IOException error) {}   

        System.out.println(playing);                
    }
}

1 个答案:

答案 0 :(得分:3)

每次调用music()时,都会构造一个新的输入流,因此您在方法调用之间使用绝对不同的流实例。