I'm working with my pet project. This is an application that can play online and local songs. I've done the play online songs task, but I'm stuck in playing local songs.
I've listed all local songs but I cannot play the song because the method startMusic in my MusicService is only for online songs. I don't know how to set the data source for local songs.
This is the function startMusic in my MusicService file
fun startMusic(song: Music) {
isServiceStart = true
music = song
position = music.position - 1
mediaPlayer.reset()
mediaPlayer.setDataSource("https://api.mp3.zing.vn/api/streaming/audio/${song.id}/320")
mediaPlayer.prepare()
mediaPlayer.start()
sendActionToActivity(AppConstants.ACTION_START)
sendMusicToActivity(music)
sendNotificationMedia(song, true)
mediaPlayer.setOnCompletionListener {
playNextSong()
}
}
This is how I get the list of local songs
private fun getMusic(): MutableList<Music> {
val musicList = mutableListOf<Music>()
val projection = arrayOf(
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION
)
val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0"
val sortOrder = "${MediaStore.Audio.Media.TITLE} ASC"
requireContext().contentResolver.query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
sortOrder
)?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)
val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
var position = 0
while (cursor.moveToNext()) {
val id = cursor.getString(idColumn)
val title = cursor.getString(titleColumn)
val artist = cursor.getString(artistColumn)
val data = cursor.getString(dataColumn)
val duration = cursor.getInt(durationColumn) / 1000 // Convert to seconds
val music = Music(id, title, artist, data, position++, "local", duration, "")
musicList.add(music)
}
}
return musicList
}