可以支持mp3 文件的播放、暂停、停止等。
Mainactivity界面主要代码
class MainActivity : AppCompatActivity() {
private val mediaPlayer = MediaPlayer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initMediaPlayer()
val button1:Button = findViewById(R.id.play)
val button2:Button = findViewById(R.id.pause)
val button3:Button = findViewById(R.id.stop)
button1.setOnClickListener {
if(!mediaPlayer.isPlaying){
mediaPlayer.start()
}
}
button2.setOnClickListener {
if(mediaPlayer.isPlaying){
mediaPlayer.pause()
}
}
button3.setOnClickListener {
if(mediaPlayer.isPlaying){
mediaPlayer.reset()
initMediaPlayer()
}
}
}
private fun initMediaPlayer(){
val assetManager = assets
val fd = assetManager.openFd("music.mp3")
mediaPlayer.setDataSource(fd.fileDescriptor,fd.startOffset,fd.length)
mediaPlayer.prepare()
}
override fun onDestroy() {
super.onDestroy()
mediaPlayer.stop()
mediaPlayer.release()
}
}
布局界面代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="play"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="pause"/>
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop"/>
</LinearLayout>
注意:在app/src/main目录下创建assets文件夹,并放入mp3文件