简体   繁体   English

如何使用java.applet.AudioClip?

[英]How to use java.applet.AudioClip?

I would like to ask you how to use the java.applet.AudioClip. 我想问你如何使用java.applet.AudioClip。 I have tried to use it, but I could not figure out how to use it. 我尝试使用它,但是我不知道如何使用它。 Thanks for your help. 谢谢你的帮助。

Here is how I implement the AudioClip class: 这是我实现AudioClip类的方法:

AudioClip clip = Applet.newAudioClip(url);

Where url is the URL object that points to my sound file. 其中url是指向我的声音文件的URL对象。 You can get the URL object multiple ways, but I use this (because it always works for me): 您可以通过多种方式获取URL对象,但是我使用了它(因为它始终对我有用):

URL url = getClass().getClassLoader().getResource("sound1.wav");

And then to play the sound, call the clip's play method on a new Thread: 然后要播放声音,请在新的线程上调用剪辑的play方法:

new Thread() {
    public void run() {
        clip.play();
    }
}.start();

Here's an example of a Sound class you could use to play your audio clips: 这是一个Sound类的示例,您可以使用它播放音频剪辑:

public class Sound {

    public static final Sound[] sounds = {
        new Sound("sound1.wav"),
        new Sound("sound2.wav")
    };

    private AudioClip clip;

    private Sound(String name) {
        clip = Applet.newAudioClip(getClass().getClassLoader().getResource(name));
    }

    public void play() {
        new Thread() {
            public void run() {
                clip.play();
            }
        }.start();
    }

}

Just define all of your sounds in the static Sound array, and call those when you need to use the sound: 只需在静态Sound数组中定义所有声音,然后在需要使用声音时调用它们即可:

//anywhere outside of the Sound class
//(will play "sound1.wav" in this example)
Sound.sounds[0].play();

Hope this helped you! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM