用Java播放声音

Day*_*Day 1 java audio

您好我正在尝试在java中播放声音,代码如下所示:

public void playSound(String sound) {
    try {
        InputStream in = new FileInputStream(new File(sound));
        AudioStream audio = new AudioStream(in);
        AudioPlayer.player.start(audio);
    } catch (Exception e) {}
}
Run Code Online (Sandbox Code Playgroud)

我导入了sun.audio*; 但是得到一个错误:

访问限制:"AudioPlayer"类型不是API(对所需库'C:\ Program Files\Java\jre7\lib\rt.jar'的限制)

Nik*_*ntz 7

如果我们使用javax.sound,下面的程序会从eclipse播放16位的wav声音.

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 {

   // Constructor
   public SoundClipTest() {
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test Sound Clip");
      this.setSize(300, 200);
      this.setVisible(true);       
      // You could also get the sound file with a URL
      File soundFile = new File("C:/Users/niklas/workspace/assets/Sound/sound.wav");
      try ( // Open an audio input stream.            
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);            
            // 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();
   }
}
Run Code Online (Sandbox Code Playgroud)

  • Nit pick:你真的不需要框架,它只是杂乱无章,但是说过,没有理由延伸到`JFrame`,因为你没有为类添加任何新功能而你应该确保UI在Event Dispatching Thread的上下文中构造.有关详细信息,请参阅[初始线程](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) (2认同)