在Java中使用AudioPlayer

时间:2011-04-27 13:22:45

标签: java swing

在我的swing应用程序中,我使用一个类来点击鼠标时发出声音。我遇到的问题是,当我打电话给班级时,一次播放声音,当突然点击另一个按钮时,它不会播放声音。我尝试延迟我的代码,但仍然无法正常工作。这与线程有关吗?我不擅长线程所以请告诉我如何做到这一点。我使用的代码如下,

package utilities;  
import java.applet.AudioClip;  
import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;   
import java.net.URL;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
import sun.audio.AudioData;  
import sun.audio.AudioPlayer;  
import sun.audio.AudioStream;  
import sun.audio.ContinuousAudioDataStream;  
public class Tone {`  

    File wavFile = new File("sounds/Windows Default.wav");
    URL urlClick = Tone.class.getResource("/sounds/WindowsDefault.wav");
    AudioClip sound;
    public void sound() {
        AudioStream as = null;
        try {

            InputStream in = this.getClass().getResourceAsStream("/sounds/WindowsDefault.wav");
            as = new AudioStream(in);
            AudioData data = as.getData();
// Create ContinuousAudioDataStream.
ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data);
            //System.out.println(as.getLength());
            AudioPlayer.player.start(cas);

            //System.out.println(urlClick);
                //sound = Applet.newAudioClip(urlClick);
        //this.wait(1000);
           for(int i =0;i<100000;i++){
               double k = Math.pow(i, 5);
               if(i==99999){
                   AudioPlayer.player.stop(cas);
                   return;
               }
           }
           // sound.play();
            String relativeDirectory = System.getProperty("user.dir");
            System.out.println(relativeDirectory);

        } catch (IOException ex) {
            Logger.getLogger(Tone.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                as.close();
            } catch (IOException ex) {
                Logger.getLogger(Tone.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }

    public static void main(String[] args) {
Tone tone = new Tone();
tone.sound();
System.out.println("done");

    }
}

- EDIT-- 我之所以使用continuousaudiostream是因为当我使用这个aleast听到一些声音时声音根本没有发生。即使我使用AudioStream,问题仍然存在..

2 个答案:

答案 0 :(得分:3)

1)最好不要使用隐藏的类/ api - 因为你已经读过你在其他问题中的链接: - )

2)在开始/重新打开之前停止/关闭已经运行的声音,在公共场合如下:

Clip clip;

private void doPlay(final String url) {
    try {
        stopPlay();
        AudioInputStream inputStream = AudioSystem
                .getAudioInputStream(getClass().getResourceAsStream(url));
        clip = AudioSystem.getClip();
        clip.open(inputStream);
        clip.start();
    } catch (Exception e) {
        stopPlay();
        System.err.println(e.getMessage());
    }
}

private void stopPlay() {
    if (clip != null) {
        clip.stop();
        clip.close();
        clip = null;
    }
}

(注意:完全关闭仅用于说明,优化逻辑以加载一次,然后再次停止/启动)

答案 1 :(得分:1)

看起来ContinuousAudioDataStream仅在文件结束后重置,因此可能是在发生这种情况之前发生了第二次按钮单击。也许尝试重置流