Issue
How to apply start/stop function for ToggleButton
or normal Button
?
The problem is it doesn't stop/start after the first attempt! It works only once (it should change every time the user clicked the button).
Music ToggleButton
<ToggleButton
android:id="@+id/music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ToggleButton" />
Background Music function
fun BackgroundMusic() {
val mp = MediaPlayer.create(this, R.raw.sudani)
mp.start()
music.setOnClickListener {
if (mp.isPlaying) {
mp.stop()
} else if (!mp.isPlaying) {
mp.start()
}
}
}
Solution
Please take a deep look into the MediaPlayer javadoc. There you can read something like this:
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
- Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
Basically it means you have to call prepare()
before you call start()
again:
fun BackgroundMusic() {
val mp = MediaPlayer.create(this, R.raw.sudani)
mp.start()
music.setOnClickListener {
if (mp.isPlaying) {
mp.stop()
} else if (!mp.isPlaying) {
try {
mp.prepare()
mp.start()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
Answered By - StefMa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.