无法使用媒体播放器在api 24上播放原始声音文件

时间:2018-10-07 10:27:56

标签: android android-mediaplayer

根据文档,this基本上就是您播放声音的方式。它可以在Android 19(Kitkat)上运行,但在24(牛轧糖)上,我一直收到准备失败的消息:status = 0x1异常。

private fun playSound() {

     try {    
            val mediaPlayer: MediaPlayer? = MediaPlayer.create(this, 
             R.raw.splashtitle)
            mediaPlayer?.start() // no need to call prepare(); create() does 
             that for you
            } catch (e: IOException) {
            Toast.makeText(this,"Play failed",Toast.LENGTH_LONG).show()
        }
}

在运行时授予api 23+的权限

 private fun checkPermission() {
    if (Build.VERSION.SDK_INT >= 23) {

        // if 23
        // prepare permissions

        val permissionsToRequest = ArrayList<String>()


        if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }


        if (permissionsToRequest.size > 0) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toTypedArray(), 101)
        } else {
            playSound()
        }
    } else {
        playSound()

    }
}

0 个答案:

没有答案