I have created a Fragment/Activity using MediaPlayer class. It has a "Play Music" button. When clicked, it plays music without stopping. I want a "Play Music" button, that plays music always from the start when the user tapped the button. I am using KOTLIN.
I have used two different type of code -
1st, When I used it in My fragment Activity, getAssets() error showed and It's not working -
class TEST : Fragment() {
val mp = MediaPlayer()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.test, null)
}
override fun onResume() {
super.onResume()
(activity as MainActivity)
.setActionBarTitle("TEST")
but.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
if (mp.isPlaying) {
mp.stop()
}
try {
mp.reset()
val afd: AssetFileDescriptor
afd = getAssets().openFd("AudioFile.mp3")
mp.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
mp.prepare()
mp.start()
} catch (e: IllegalStateException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
})
}
}
2nd, when I used it, Its not showed any error but not working-
button.setOnClickListener {
val mp = MediaPlayer.create(getActivity(), R.raw.sound1)