Biken
Biken

Reputation: 71

How to play Audio file from resource directory in android

I'm not able to play a small 2 second audio clip. I have tried every permutation mentioned in stackOverflow similar to this problem. Nothing is working for me even the solution that seem to be work for others. I don't know whether it's because I don't have a physical device to test on or something.

I'm getting Activity not found error :

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.category.ACTION_VIEW dat=R.raw.song_name.mp3 }

My code for playing audio to :

Uri uri = Uri.parse("R.raw.song_name.mp3");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("audio/*");
intent.setData(uri);
startActivity(intent);

My file is stored at :

res/raw/song_name.mp3

I haven't done anything extra on AndroidManifest.xml. I'm running this app on emulator. Is this causing this error ?

Upvotes: 2

Views: 6420

Answers (2)

Rishabh Chaudhary
Rishabh Chaudhary

Reputation: 91

Instead of using Intent you can use MediaPlayer class.

MediaPlayer mp;
mp=MediaPlayer.create(getApplicationContext(),R.raw.song_name.mp3);
mp.start();

I hope this works.

Upvotes: 9

krughanh
krughanh

Reputation: 21

It seems like your code is not complete with respects to broadcasting and mediaPlayer

I suggest you to read about media player here https://developer.android.com/reference/android/media/MediaPlayer.html

for intents you may check here https://developer.android.com/guide/components/broadcasts.html

//to play a local file you could do it this way 

 //create a new media player
        MediaPlayer mPlayer = new MediaPlayer();
//obtain the source
        try {
            mPlayer.setDataSource("path/to/youraudiofile.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
//prepare the player
        try {
            mPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
//now start the player to begin playing the audio
        mPlayer.start();

Upvotes: 1

Related Questions