0

I'm new in android development trying to play a simple audio file. I organized my audio files in multiple nested folders.

Here is the complete source on disk "app/src/main/res/raw/sounds/first/nested/my_sound_1.mp3" ... Certainly there are other files in different folders.

This is the method I'm using to play the audio file

fun audioPlayer(path : String, fileName: String) {

   var mediaPlayer = MediaPlayer()

    try {
        mediaPlayer.setDataSource(path + File.separator + fileName)
        mediaPlayer.prepare()
        mediaPlayer.start()

    } catch (e: Exception) {
        e.printStackTrace()
    }

}

and on a button click event I'm using this code

audioPlayer("raw.sounds.first.nested", "my_sound_1.mp3")

Here is the error.

java.io.IOException: setDataSource failed.
Naveed Abbas
  • 1,157
  • 1
  • 14
  • 37

1 Answers1

0

Here is the complete source on disk "app/src/main/res/raw/sounds/first/nested/my_sound_1.mp3"

First, that would appear to be a file on your development machine, that you are trying to package into your app as a raw resource.

Second, resource directories cannot have subdirectories. You need to get rid of sounds/first/nested/ and put your MP3 file in to raw/.

This is the method I'm using to play the audio file

A resource is a file on your development machine. It is not a file on the device.

There is a static create() method on MediaPlayer that takes a Context and a resource ID. Use that instead:

fun audioPlayer(context: Context, rawResourceId: Int) {
   val mediaPlayer = MediaPlayer(context, rawResourceId)

   mediaPlayer.prepare()
   mediaPlayer.start()
}

and call it from your activity or service as audioPlayer(this, R.raw.my_sound_1).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • What if I want to keep the directory structure in the packaged app. Is there any way to add these folders to the packaged app? – Naveed Abbas Jul 21 '18 at 07:48
  • @ToughGuy: Not as raw resources. `assets/` allows you to have an arbitrary directory structure, but [playing media from there is a bit more difficult](https://stackoverflow.com/q/3289038/115145). – CommonsWare Jul 21 '18 at 10:31