Example of adding background music to JAVA application:
1. First define a URL object and assign NULL value;
URL ? musicURL ? = ? null; ?
2. Then assign a value to the defined URL, that is, get the URL address to be played,
musicURL ? = ? new ? URL("Music Address"); //Get the URL to be played The url for playing music
3. Create an instance of playing audio and get this instance
AudioClip ? ac ? = ? Applet.newAudioClip(musicURL); ? //Get a playback Audio example
4. Control playback
ac.play(); ? //Play the first episode
ac.loop(); ? // Loop play
ac.stop(); //Stop
Play local music example:
private void playMusic(){
try {
javax.media.Player player;
if(null==player){
File musicFile=new File("./music.mp3 ");//Get an MP3 file
if(musicFile.exists()){
MediaLocator ?locator=new MediaLocator("file:"+musicFile.getAbsolutePath()) ;
player = Manager.createRealizedPlayer(locator);
player.prefetch();//Pre-read file
}else{
< p> System.err.println(pro.getMusicFile()+" not found");}
}
//centerpanel.add( player.getControlPanelComponent()!=null?player.getControlPanelComponent():null);//Display playback tools
player.start();//Play
} catch (CannotRealizeException ex) {
ex.printStackTrace();
} catch (NoPlayerException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}