您好我正试图在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) {}
}
我导入了sun.audio *;但是得到一个错误:
访问限制:“AudioPlayer”类型不是API(限制为 必需的库'C:\ Program Files \ Java \ jre7 \ lib \ rt.jar')
答案 0 :(得分:6)
如果我们使用eclipse,以下程序会播放来自javax.sound的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);
try {
// Open an audio input stream.
File soundFile = new File("C:/Users/niklas/workspace/assets/Sound/sound.wav"); //you could also get the sound file with an URL
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();
}
}