音频播放: 一个简单的音乐播放器示例代码如下: class MainActivity : AppCompatActivity() { private val mediaPlayer = MediaPlayer() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initMediaPlayer() play.setOnClickListener { if (!mediaPlayer.isPlaying) { mediaPlayer.start() // 开始播放 } } pause.setOnClickListener { if (mediaPlayer.isPlaying) { mediaPlayer.pause() // 暂停播放 } } stop.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() } }
播放视频 一个简单的视频播放器示例代码如下: class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val uri = Uri.parse("android.resource://$packageName/${R.raw.video}") videoView.setVideoURI(uri) play.setOnClickListener { if (!videoView.isPlaying) { videoView.start() // 开始播放 } } pause.setOnClickListener { if (videoView.isPlaying) { videoView.pause() // 暂停播放 } } replay.setOnClickListener { if (videoView.isPlaying) { videoView.resume() // 重新播放 } } } override fun onDestroy() { super.onDestroy() videoView.suspend() } }