1.在主mainGame 里设置music信息



private Music music;
private int musicId;
private int lastMusicId;
public int musicVoice;
public int soundVoice;


2.初始化加载



musicVoice=gameConfig.playerConfig.getInteger("music",4);
soundVoice=gameConfig.playerConfig.getInteger("sound",4);
musicId=gameConfig.geRandomtMusicId(0,0);
music = Gdx.audio.newMusic(gameConfig.getMusicFile(musicId));
music.setLooping(true);
music.setVolume(musicVoice*1f/7);
music.play();


3.记录音乐信息并加载

libgdx 播放音乐_加载



public int geRandomtMusicId(int type,int lastId) {
Array<XmlReader.Element> xmlEs=getCONFIG_MUSIC().e.getChildrenByName("music");
int musicId=lastId;
IntArray rs=game.tempUtil.getTempIntArray();
for(int i=0;i<xmlEs.size;i++){
XmlReader.Element e=xmlEs.get(i);
int id=e.getInt("id");
if(e.getInt("type",-1)==type&&id!=lastId){
rs.add(id);
}
}
if(rs.size>0){
musicId=rs.random();
game.tempUtil.disposeTempIntArray(rs);
}
Gdx.app.log("geRandomtMusicId",lastId+":"+musicId+":"+type);
return musicId;
}

public FileHandle getMusicFile(int musicId){
XmlReader.Element e=getCONFIG_MUSIC().getElementById(musicId);
if(e!=null){
return Gdx.files.internal(e.get("file"));
}
return Gdx.files.internal("audio/jokull.mp3");
}


4.播放



//ifForceLoop 是否强制设定音乐循环
public void setMusicById(int id,boolean ifForceLoop){
Gdx.app.log("playMusic",id+":"+musicVoice);
if(musicId!=id||!music.isLooping()){
lastMusicId=musicId;
musicId=id;
music.pause();
music.dispose();
music = Gdx.audio.newMusic(gameConfig.getMusicFile(musicId));
// music.setLooping(true);
music.setVolume(musicVoice*1f/7);
music.play();
if(gameConfig.getCONFIG_MUSIC().getElementById(musicId).get("play","loop").equals("loop")||ifForceLoop){
music.setLooping(true);
}else{
music.setLooping(false);
music.setOnCompletionListener(new Music.OnCompletionListener() {
@Override
public void onCompletion(Music aMusic) {
int musicType=gameConfig.getCONFIG_MUSIC().getElementById(musicId).getInt("type",0);
int musicId=gameConfig.geRandomtMusicId(musicType,lastMusicId);
setMusicById(musicId,false);
}
});
}
}
}
public void setMusicByType(int type){
int musicType=gameConfig.getCONFIG_MUSIC().getElementById(musicId).getInt("type",0);
if(type!=musicType){
int musicId=gameConfig.geRandomtMusicId(type,this.musicId);
setMusicById(musicId,false);
}
}


 

  5.在转换场景中加入切歌



public void toScreen(int nextScreenId) {

if(nextScreenId==81){ //获取战斗场景中的详细音乐设定
XmlReader.Element xmlE=gameConfig.getDEF_STAGE().getElementById(stageId);
int musicId=xmlE.getInt("musicId",0);
if(musicId==-1){//如果值是-1,则默认为通用战斗场景播放
int bgmType=gameConfig.getCONFIG_LAYOUT().getElementById(screenId).getInt("bgmType");
setMusicByType(bgmType);
}else {
setMusicById(musicId,true);
}
}else {//获取普通场景的音乐类型设定
int bgmType=gameConfig.getCONFIG_LAYOUT().getElementById(screenId).getInt("bgmType");
setMusicByType(bgmType);
}


-----------------场景跳转--------------------

}