InputStream is =null
AudioStream as = null
is = getClass().getResourceAsStream("a.wav")
try {
as = new AudioStream(is)
} catch (IOException e) {}
AudioPlayer.player.start(as)
此方法将音乐文件放入流中在播放,仅限于Java Application,容易报错,空指针异常,或者是流异常,不推荐。
做法二:
String music = "a.wav"
AudioClip clip = Applet.newAudioClip(getClass().getResource(music))
次方法在Applet中运行没有问题,但是Application中getclass()会返回空指针,导致失败。
推荐做法:
private URL url
private AudioClip ac
File f1 = new File("C:/3.wav")
try {
url= f1.toURL()
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
ac= Applet.newAudioClip(cb1)
ac.play()
public void play(String Filename){
try{
// 用输入流打开一音频文件
InputStream in = new FileInputStream(Filename)//FIlename 是你加载的声音文件如(“game.wav”)
// 从输入流中创建一个AudioStream对象
AudioStream as = new AudioStream(in)
AudioPlayer.player.start(as)//用静态成员player.start播放音乐
//AudioPlayer.player.stop(as)//关闭音乐播放
//如果要实现循环播放,则用下面的三句取代上面的“AudioPlayer.player.start(as)”这句
/*AudioData data = as.getData()
ContinuousAudioDataStream gg= new ContinuousAudioDataStream (data)
AudioPlayer.player.start(gg)// Play audio.
*/
//如果要用一个 URL 做为声音流的源(source),则用下面的代码所示替换输入流来创建声音流:
/*AudioStream as = new AudioStream (url.openStream())
*/
} catch(FileNotFoundException e){
System.out.print("FileNotFoundException ")
} catch(IOException e){
System.out.print("有错误!")
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)