Search code examples
androidandroid-mediaplayer

play mp3 file in resource folder not working


I want to play an mp3 file in my res/raw folder.
But i get error as "error (1, -2147483648)" and IOException on mp.prepare()

My code

try {
        MediaPlayer mPlayer = MediaPlayer.create(NavigationHome.this, R.raw.notfy);
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

I also tried with

try {
        mp.setDataSource(NavigationHome.this, Uri.parse("android.resource://com.hipay_uae/res/raw/notfy"));
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

Another solution that I tried

AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();

These too didn't work for me.


Solution

  • It will help more if you can post the StackTrace in your question.

    But, as per the information in your question, the below code should work for playing the media file from the raw resource folder.

    If you use the create() method, prepare() gets called internally and you don't need to explicitly call it.

    MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.notify);
    mediaPlayer.start();
    

    But, the point to consider is that prepare() generally throws an IllegalStateException, and in your case, you are getting an IOException. So it would be worth checking if the file is in fact present in raw folder and/or the file is corrupt.