java中Swing怎么添加音乐?
JAVA应用程序添加背景音乐示例:
1.先定义一个 URL 对象,并赋NULL值;
URL musicURL = null;
2.然后为定义的 URL 赋值,即得到要播放的URL地址,
musicURL = new URL( "音乐地址");//得到要播放音乐的url
3.创建一个播放音频的实例,并得到这个实例
AudioClip ac = Applet.newAudioClip(musicURL); //得到一个播放音频的实例
4.进行播放控制
ac.play(); //播放一编
ac.loop(); //循环播放
ac.stop();//停止
播放本地音乐示例:
private void playMusic(){
try {
javax.media.Player player;
if(null==player){
File musicFile=new File("./music.mp3");//得到一个MP3文件
if(musicFile.exists()){
MediaLocator locator=new MediaLocator("file:"+musicFile.getAbsolutePath());
player = Manager.createRealizedPlayer(locator);
player.prefetch();//预读文件
}else{
System.err.println(pro.getMusicFile()+" 找不到");
}
}
//centerpanel.add(player.getControlPanelComponent()!=null?player.getControlPanelComponent():null);//显示播放工具
player.start();//播放
} catch (CannotRealizeException ex) {
ex.printStackTrace();
} catch (NoPlayerException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
推荐于2018-03-04
URL musicUrl = new URL("file:"
+ System.getProperty("user.dir").toString()
+ "\\src\\because.mp3");
System.out.println(System.getProperty("user.dir").toString()
+ "\\src\\because.mp3");
AudioClip ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (MalformedURLException e) {
e.printStackTrace();
}
2013-07-23
2013-07-23
import java.applet.AudioClip;
import java.awt.Container;
import java.net.MalformedURLException;
import java.net.URL;import javax.swing.JApplet;
import javax.swing.JFrame;public class Music extends JApplet{
private static final long serialVersionUID = -6993483162976752835L; public static void main(String[] args) {
JFrame f=new JFrame();
Container con=new Container();
f.add(con);
f.setBounds(0, 0,200,200);
f.setVisible(true);
}}
URL musicUrl = new URL("file:"
+ System.getProperty("user.dir").toString()
+ "\\src\\because.mp3");
System.out.println(System.getProperty("user.dir").toString()
+ "\\src\\because.mp3");
AudioClip ac = Applet.newAudioClip(musicUrl);
ac.play();
} catch (MalformedURLException e) {
e.printStackTrace();
}