I am working on a music player app using kotlin. I defined a mediaPlayer object in my MainActivity and is using it in SongPlayingFragments. The problem I am having is that the next Songs are automatically playing. I tried to figure out the problem and found that my onCompletionListener isn't working or rather say, is not getting invoked. I fail to troubleshoot the problem myself and therefore is searching for any solutions or any other way to change my songs automatically.
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() Function is supposed to change my songs. The Toast "Changing song" isn't shwing up and therefore i assume that whatever the problem is, it's causing my Listener not to get invoked.
Any suggestions?
replace
mediaPlayer.setOnCompletionListener {
Toast.makeText(context, "Changing Song", Toast.LENGTH_LONG).show()
onSongComplete()
}
with
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(context, "Changing Song", Toast.LENGTH_LONG).show()
onSongComplete()
}
});
In order to invoke setOnCompletionListener()
, you should disable looping with a call to mediaPlayer.setLooping(false);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With