【问题标题】:URI from string is crashing the app. Am I using it wrong?来自字符串的 URI 使应用程序崩溃。我用错了吗?
【发布时间】:2019-06-13 07:55:26
【问题描述】:

在原始目录中,我有名为 rhode1.mp3 到 rhode49.mp3 的文件。

我需要随机播放其中一个文件,因此我随机生成一个数字并将其附加到 R.raw.rhode 以用作 URI(以下代码中的 uri1),但它会使应用程序崩溃。例如,当我将 uri1 替换为 R.raw.rhode1 时,它可以正常工作并播放音频文件。

我试过写R.raw.rhode$note1.mp3,但还是不行。也试过了:

("R.raw.rhode" + note1.toString() + ".mp3")

还有:

("R.raw.rhode" + note1.toString())

覆盖 fun onCreate (savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var mediaplayer: MediaPlayer? = null
    val letsgo = findViewById<Button>(R.id.start)
    val think = findViewById<SeekBar>(R.id.think)
    val extime = findViewById<SeekBar>(R.id.extime)
    val rpt = findViewById<SeekBar>(R.id.rpt)
    val rtime = findViewById<SeekBar>(R.id.rtime)
    var note1: Int
    var uri1: Uri

    letsgo.setOnClickListener {

        note1 = Random.nextInt(49) + 1
        uri1 = Uri.parse("R.raw.rhode" + note1.toString())
        mediaplayer = MediaPlayer.create(applicationContext, uri1)
        mediaplayer!!.start()
    }
}

【问题讨论】:

标签: string android-studio kotlin uri


【解决方案1】:

R.resourceType.resourceName 从编程语言的角度来看是一个有效的符号。但显然,它不是 URL/URI。

以下是如何构造资源 URI 的示例:https://stackoverflow.com/a/7979084/3050249

【讨论】:

  • 昨天尝试修复此问题 3 小时(徒劳无功)。非常感谢。对于有同样问题的人,修复:uri1 = Uri.parse("android.resource://" + getPackageName() + "/raw/rhode" + note1.toString()) 出于某种原因:uri1 = Uri.在该链接中也提出的 parse("android.resource://" + getPackageName() + "/R.raw.rhode" + note1.toString()) 不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2020-05-24
相关资源
最近更新 更多