Visakh
Visakh

Reputation: 259

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.

Upvotes: 0

Views: 1518

Answers (3)

anemo
anemo

Reputation: 1367

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.

Upvotes: 3

vikrant arankalle
vikrant arankalle

Reputation: 278

Try this

String fname="your_filename";
int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
mediaPlayer.start();

Upvotes: -1

MashukKhan
MashukKhan

Reputation: 1954

Try to initialize your media player before preparing it or setting data source to it

Play From external directory

String filePath = Environment.getExternalStorageDirectory()+"/folderName/yourfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

From raw folder

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

Upvotes: 1

Related Questions