解决方案
/**
* 播放raw目录下文件
*/
private fun playFromRaw(): MediaPlayer? {
mediaPlayer = MediaPlayer.create(this, R.raw.test)
mediaPlayer.start()
return mediaPlayer
}
/**
* 播放assets目录下文件
*/
private fun playFromAssets(): MediaPlayer {
val fd = assets.openFd("test.mp3")
mediaPlayer = MediaPlayer()
mediaPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
mediaPlayer.prepare()
mediaPlayer.start()
return mediaPlayer
}
/**
* 播放SD卡上文件
* 需要动态申请SD读权限
*/
private fun playFromSdCard(): MediaPlayer {
val path = "/sdcard/test.mp3"
mediaPlayer = MediaPlayer()
mediaPlayer.setDataSource(path)
mediaPlayer.prepare()
mediaPlayer.start()
return mediaPlayer
}
/**
* 播放URL对应文件
*/
private fun playFromUrl(): MediaPlayer {
val audioUrl = "https://gitee.com/cxyzy1/audioPlayerDemo/raw/master/test.mp3" //这里给一个歌曲的网络地址就行了
val uri = Uri.parse(audioUrl)
mediaPlayer = MediaPlayer.create(this, uri)
mediaPlayer.start()
return mediaPlayer
}
Demo源代码
https://gitee.com/cxyzy1/audioPlayerDemo.git
附录
Android中的音频播放(MediaPlayer和SoundPool)
安卓开发技术分享: https://www.jianshu.com/p/442339952f26
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」
网友评论