java - 如何使用 Kotlin 使用路径播放 Mp3 文件?

标签 java android-studio kotlin uri android-music-player

我开始了一个制作音乐播放器的项目。最初我已经使用 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/

相关文章:

kotlin - 在Kotlin中使用哪个标准库

java - 如何在 ubuntu 16.04 机器上安装和配置 HSQL DB

java - mappedBy 指的是类名还是表名?

android-studio - 为什么三星 Galaxy S10 Plus 皮肤在 Android Studio 中看起来很奇怪?

android - com.android.dex.DexException : Multiple dex files define Landroid/support/annotation/AnimRes;

android - 在 Jetpack Compose 中使用 LaunchedEffect 与 SideEffect

java - 任务 ':compileDebugJavaWithJavac 执行失败

java - 安全-在java中解密 "BadPaddingException"

java - 无法在 android 中将 Drawable 转换为 LayerDrawable

multithreading - Kotlin:如何调用可挂起函数而不等待其结果?