我正在使用Kotlin开发音乐播放器应用.我在MainActivity中定义了一个mediaPlayer对象,并在SongPlayingFragments中使用它.
我遇到的问题是下一首歌曲会自动播放.
我试图找出问题所在,发现我的onCompletionListener无法正常工作,或者说没有被调用.
我自己无法解决问题,因此正在寻找任何解决方案或任何其他方式来自动更改我的歌曲.
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
CurrentSongHelper.isPlaying=true
CurrentSongHelper.isShuffle= false
CurrentSongHelper.isLoop = false
var path: String ?= null
var _songArtist: String ?= null
var _songTitle: String ?= null
var songId: Long = 0
try {
path = arguments?.getString("path")
_songArtist = arguments?.getString("SongArtist")
_songTitle = arguments?.getString("SongTitle")
songId = arguments?.getInt("SongId")!!.toLong()
currentPosition = arguments!!.getInt("SongPosition")
fetchSongs = arguments?.getParcelableArrayList("SongData")
CurrentSongHelper.songPath=path
CurrentSongHelper.songArtist= _songArtist
CurrentSongHelper.songTitle= _songTitle
CurrentSongHelper.songId= songId
CurrentSongHelper.currentPosition= currentPosition
updateTextViews(CurrentSongHelper?.songTitle as String,CurrentSongHelper?.songArtist as String)
}catch (e: Exception){
e.printStackTrace()
}
//processInformation(mediaPlayer as MediaPlayer)
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
try {
mediaPlayer.setDataSource(myActivity as Context,Uri.parse(path))
mediaPlayer.prepare()
mediaPlayer.start()
}catch (e: Exception){
e.printStackTrace()
}
processInformation(mediaPlayer)
if(CurrentSongHelper.isPlaying ){
playPauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
}else{
playPauseImageButton?.setBackgroundResource(R.drawable.play_icon )
}
mediaPlayer.setOnCompletionListener {
Toast.makeText(context,"Changing Song",Toast.LENGTH_LONG).show()
onSongComplete()
}
clickHandler()
audioVisualization?.linkTo(mediaPlayer)
}
onSongComplete()函数应该更改我的歌曲.
Toast的“ Changing song”并没有消失,因此我认为无论出现什么问题,它都会导致我的Listener无法被调用.
有什么建议么?
最佳答案
更换
mediaPlayer.setOnCompletionListener {
Toast.makeText(context,Toast.LENGTH_LONG).show()
onSongComplete()
}
与
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(context,Toast.LENGTH_LONG).show()
onSongComplete()
}
});