I want to make a simple piano app.
I want the sound to sound only while the button is pressed, and stop when it is released.
I made the following code.
When you press the button for the first time after starting the app, the sound is played, and when you release your finger, it stops even during playback.
However, after the second time, it will not stop even if you release your finger during playback.
Why is this?
Also, how can I stop when I release my finger after the second time?
I would be pleased if someone could answer.
button.setOnTouchListener (View.OnTouchListener {view, motionEvent->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN->{
soundPool.play (soundResId, 1.0f, 1.0f, 0, 0, 1.0f)
}
}
return @ OnTouchListener false
})
button.setOnClickListener (View.OnClickListener {
soundPool.stop (soundResId)
})
I tried to make ACTION_UP with when as below, but I couldn't.
button.setOnTouchListener (View.OnTouchListener {view, motionEvent->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN->{
soundPool.play (soundResId, 1.0f, 1.0f, 0, 0, 1.0f)
}
MotionEvent.ACTION_UP->{
soundPool.stop (soundResId)
}
}
return @ OnTouchListener false
})
Execution environment
windows10
androidstudio3.5
kotlin 1.3.60
-
Answer # 1
-
Answer # 2
It seems that it is necessary to stop with the ID of the return value when playing.
var sPlayId should be a variable that can be seen in the class.
I haven't used kotlin so I don't know if it matches with var. .If you can't fix this, stop would release the native resource, so you may need to load again.
var sPlayId button.setOnTouchListener (View.OnTouchListener {view, motionEvent-> when (motionEvent.action) { MotionEvent.ACTION_DOWN->{ sPlayId = soundPool.play (soundResId, 1.0f, 1.0f, 0, 0, 1.0f) } } return @ OnTouchListener false }) button.setOnClickListener (View.OnClickListener { soundPool.stop (sPlayId) })
- android - i want to perform a screen transition and set the button tap event of the transitioned second screen to "display
- android - adding a character string does not work in kotlin's calculator app
- passing values using bundle between android fragments
- android - i want to change the screen after clearapplicationuserdata
- java - how can i make sure that the font size is always full on android?
- android - i want to display the open source license from the setting screen
- how to get the date set on your android device
- android - when i close a custom dialogfragment nested in fragmentcontainerview and then reopen it, the display collapses
- i want to display in detail the images displayed in the list when transitioning from the list to the detail page in recyclerview
- android - [kotlin] after replacing the page with replacefragment, i want to use the button on the screen to implement the return
It seems to be correct to give the streamID obtained by the return value of SoundPool # play () to the argument of SoundPool # stop (). If you feel like the following, can you stop it?