用 Java 播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25171205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Playing Sound in Java
提问by Day
Hello I'm trying to play a sound in java the code looks like this:
您好,我正在尝试在 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) {}
}
I imported sun.audio*; however get an error:
我导入了 sun.audio*; 但是得到一个错误:
Access restriction: The type 'AudioPlayer' is not API (restriction on required library 'C:\Program Files\Java\jre7\lib\rt.jar')
访问限制:'AudioPlayer' 类型不是 API(对所需库'C:\Program Files\Java\jre7\lib\rt.jar'的限制)
回答by Niklas
The following program plays a 16-bit wav sound from eclipseif we use javax.sound.
如果我们使用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();
}
}