How can I play sound in Java?

后端 未结 10 814
傲寒
傲寒 2020-11-22 04:38

I want to be able to play sound files in my program. Where should I look?

10条回答
  •  再見小時候
    2020-11-22 05:20

    I'm surprised nobody suggested using Applet. Use Applet. You'll have to supply the beep audio file as a wav file, but it works. I tried this on Ubuntu:

    package javaapplication2;
    
    import java.applet.Applet;
    import java.applet.AudioClip;
    import java.io.File;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class JavaApplication2 {
    
        public static void main(String[] args) throws MalformedURLException {
            File file = new File("/path/to/your/sounds/beep3.wav");
            URL url = null;
            if (file.canRead()) {url = file.toURI().toURL();}
            System.out.println(url);
            AudioClip clip = Applet.newAudioClip(url);
            clip.play();
            System.out.println("should've played by now");
        }
    }
    //beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav
    

提交回复
热议问题