
public void sing(String fileName) {// fileName为加载声音文件的相对路径
URL url = test.class.getResource(fileName)//
// 此句不要的话,fileName就只能是声音文件的绝对路径,为可移
// 植起见,建议不要省略
try {
InputStream is = url.openStream()// 获得音乐文件的输入流
//InputStream is = new FileInputStream(new File(fileName))
AudioStream as = new AudioStream(is)
AudioPlayer.player.start(as)// 用AudioPlayer静态成员player.start播放音乐
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "音乐文件未找到!", "错误提 示",
JOptionPane.WARNING_MESSAGE)
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "出现未知错误!", "错 误",
JOptionPane.ERROR_MESSAGE)
}
}
public void loopSing(final String fileName) {// fileName为加载声音文件的相对路径
final URL url = test.class.getResource(fileName)//
// 此句不要的话,fileName就只能是声音文件的绝对路径,为可移
// 植起见,建议不要省略
new Thread() {
public void run() {
while (true) {
try {
InputStream is = url.openStream()
AudioStream as = new AudioStream(is)
AudioPlayer.player.start(as)// 用AudioPlayer静态成员player.start播放音乐
Thread.sleep(57500)
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "音乐文件未找到!",
"错误提 示", JOptionPane.WARNING_MESSAGE)
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "出现未知错误!", "错 误",
JOptionPane.ERROR_MESSAGE)
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
}.start()
}
}
以前写的一段代码。你看看吧。好像只能播放wav格式的
URL url = test.class.getResource(fileName)
test是和wav放在同一个文件夹下的Java类,用来做标识的,里面没东西。
java中可以使用AudioPlayer来播放音乐,实例如下:
public class MySound{public MySound(){
//C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar这个jar包怎么加进工程,我放在那个工程中也没用
try {
InputStream in = new FileInputStream("hello.wav")//找到这个音乐文件
AudioStream as = new AudioStream(in)
AudioPlayer.player.start(as)// 开始播放
//AudioPlayer.player.stop(as)
}catch(FileNotFoundException e){
}
catch(IOException e){
}
}
public static void main(String[] args) {
new MySound3()
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)