我开始了一个制作音乐播放器的项目。最初我已经使用 ApI 级别 29 列出了所有 mp3 文件。但是我在创建媒体播放器时遇到了问题。每次显示的错误都是“找到空 Uri”。 ..我已经尝试过这个... fun getAppExternalFilesDir():文件? { 返回 if (Build.VERSION.SDK_INT >= 29) { 获取外部文件目录(空) } else {//@Deprecated 在 API 29 中已弃用。 ///存储/模拟/0 环境.getExternalStorageDirectory() } }
fun ListDir(f: File) {
var files: Array<File>? = f.listFiles()
list.clear()
if (files != null) {
for (file: File in files) {
if (file.name.endsWith(".mp3")){
list.add(Model(file.name))
}
}
}
listview.setOnItemClickListener { parent:AdapterView<*>, view:View, position:Int, id:Long ->
if (position>=0) {
var textcopy: TextView = view.findViewById(R.id.foldername)
var namecopied: String = textcopy.text.toString()
mediaplayer = MediaPlayer()
var uri: Uri = Uri.parse((getAppExternalFilesDir().toString() + "/" + namecopied))
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show()
mediaplayer = MediaPlayer.create(this, uri)
mediaplayer.prepare()
mediaplayer.start()
}
//where getAppExternalFilesDir() =getExternalFilesDir(null)
}
最佳答案
您的代码也没有优化,您可以使用冷序列来搜索文件,它会在运行时破坏文件的旧实例
fun ListDir(f: File) {
val mp3Files = f.walk().map { it.absolutePath }.filter { it.endsWith(".mp3") }.toList()
listview.setOnItemClickListener { parent:AdapterView<*>, view:View, position:Int, id:Long ->
if (position>=0) {
...
var uri: Uri = Uri.fromFile(File(mp3Files[position]))
...
}
}
}
这将创建正确的 Uri,您可以将其传递给媒体播放器来播放 mp3 文件。
关于java - 如何使用 Kotlin 使用路径播放 Mp3 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61424606/