I'm having trouble getting the audio file path and sending him to mediaPlayer.create
below is the code I have to get the file path.
the control sound function is to receive the file and play.
val resolver: ContentResolver = contentResolver
val uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = resolver.query(uri, null, null, null, null)
when {
cursor == null -> {
// query failed, handle error.
}
!cursor.moveToFirst() -> {
// no media on the device
}
else -> {
val titleColumn: Int = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE)
val idColumn: Int = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID)
do {
val thisId = cursor.getLong(idColumn)
val thisTitle = cursor.getString(titleColumn)
// ...process entry...
} while (cursor.moveToNext())
}
}
cursor?.close()
val id: Long = 0
val contentUri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id )
controlSound(contentUri)
mp = MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(applicationContext, contentUri)
}
}
private fun controlSound(id: Uri){
fab_play.setOnClickListener{
if (mp == null){
mp = MediaPlayer.create(this, id)
Log.d("MediaPlayer", "ID: ${mp!!.audioSessionId}")
initialiseSeekBar()
}
mp?.start()
Log.d("MediaPlayer", "Duration: ${mp!!.duration/1000} seconds")
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…