How can I play sound in Java?

后端 未结 10 797
傲寒
傲寒 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:11

    For playing sound in java, you can refer to the following code.

    import java.io.*;
    import java.net.URL;
    import javax.sound.sampled.*;
    import javax.swing.*;
    
    // To play sound using Clip, the process need to be alive.
    // Hence, we use a Swing application.
    public class SoundClipTest extends JFrame {
    
       public SoundClipTest() {
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          this.setTitle("Test Sound Clip");
          this.setSize(300, 200);
          this.setVisible(true);
    
          try {
             // Open an audio input stream.
             URL url = this.getClass().getClassLoader().getResource("gameover.wav");
             AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
             // Get a sound clip resource.
             Clip clip = AudioSystem.getClip();
             // Open audio clip and load samples from the audio input stream.
             clip.open(audioIn);
             clip.start();
          } catch (UnsupportedAudioFileException e) {
             e.printStackTrace();
          } catch (IOException e) {
             e.printStackTrace();
          } catch (LineUnavailableException e) {
             e.printStackTrace();
          }
       }
    
       public static void main(String[] args) {
          new SoundClipTest();
       }
    }
    

提交回复
热议问题