How can I play sound in Java?

后端 未结 10 763
傲寒
傲寒 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();
       }
    }
    
    0 讨论(0)
  • 2020-11-22 05:12

    I wrote the following code that works fine. But I think it only works with .wav format.

    public static synchronized void playSound(final String url) {
      new Thread(new Runnable() {
      // The wrapper thread is unnecessary, unless it blocks on the
      // Clip finishing; see comments.
        public void run() {
          try {
            Clip clip = AudioSystem.getClip();
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(
              Main.class.getResourceAsStream("/path/to/sounds/" + url));
            clip.open(inputStream);
            clip.start(); 
          } catch (Exception e) {
            System.err.println(e.getMessage());
          }
        }
      }).start();
    }
    
    0 讨论(0)
  • 2020-11-22 05:12

    There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.

    I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.

    http://stephengware.com/projects/soundtoclass/

    0 讨论(0)
  • 2020-11-22 05:16

    I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

    private static void playSound(String sound){
        // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
        URL file = cl.getResource(sound);
        final Media media = new Media(file.toString());
        final MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();
    }
    

    Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

    static{
        JFXPanel fxPanel = new JFXPanel();
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 05:24

    For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().

    What worked for me was the following:

    void playSound(String soundFile) {
        File f = new File("./" + soundFile);
        AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
        Clip clip = AudioSystem.getClip();
        clip.open(audioIn);
        clip.start();
    }
    

    And I would play the sound with:

     playSound("sounds/effects/sheep1.wav");
    

    sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).

    0 讨论(0)
提交回复
热议问题