我是Android应用程序开发的新手,这是我的第一个应用程序。 我正在建立一个音乐播放器,我有以下方法
public void playSong(int songIndex){
// Play song
mContext = getApplicationContext();
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT){
mp.pause();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mp.start();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
mp.stop();
}
}
};
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback.
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当歌曲完成时,它应该开始播放下一首歌,但事实并非如此。然后我播放切换到默认媒体播放器并切换回我的应用程序,它播放应用程序。 我想这与音频焦点有关。如何确定它是否已经具有焦点或释放重点完成。 谢谢!
答案 0 :(得分:0)
你试过这个吗?
@Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if(isRepeat){
// repeat is on play same song again
//playSong(currentSongIndex);
songPlayOnThread(currentSongIndex);
} else if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
//playSong(currentSongIndex);
playsong(currentSongIndex);
} else{
// no repeat or shuffle ON - play next song
if(currentSongIndex < (songsList.size() - 1)){
String result=playSong(currentSongIndex + 1);
if(result!="success")
{
// mp.stop();
// currentSongIndex=0;
}
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
// playSong(0);
currentSongIndex = 0;
}
}
}