40

In MediaPlayer.create method an id to a Raw file can be used but how to use that in setDataSource method?

istovatis
  • 1,408
  • 14
  • 27
russoue
  • 5,180
  • 5
  • 27
  • 29

3 Answers3

63

Refer to the source android.media.MediaPlayer

AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
if (afd == null) return;
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();

You may want to add try-catch to the block.

Chris.Zou
  • 4,506
  • 6
  • 31
  • 38
  • 2
    Thanks very much! I incorporated this into the following answer which contains a full function for playing an alarm sound from a resource: https://stackoverflow.com/a/53390067/826946 – Andy Weinstein Nov 20 '18 at 09:46
  • 1
    why are you calling `afd.close()` immediately after? doesn't that invalidate the descriptor so it can't be used??? – Michael Aug 11 '19 at 20:50
21

paraphrasing @Kartik's answer here Get URI of .mp3 file stored in res/raw folder in android

If you want to get any resource URI then there are two ways :

  1. Using Resource Name

Syntax : android.resource://[package]/[res type]/[res name]

Example : Uri.parse("android.resource://com.my.package/drawable/icon");

  1. Using Resource Id

Syntax : android.resource://[package]/[resource_id]

Example : Uri.parse("android.resource://com.my.package/" + R.drawable.icon);

These were the examples to get the URI of any image file stored in drawable folder. Similarly you can get URIs of res/raw folder.

IMO the second way would be preferred as renaming the resource etc can be easily refactored.

Set the data source like so:

CONSTANTS.RES_PREFIX = "android.resource://com.my.package/"
mp.setDataSource(getApplicationContext(),
              Uri.parse(CONSTANTS.RES_PREFIX + R.raw.id));
Community
  • 1
  • 1
Dheeraj Bhaskar
  • 18,633
  • 9
  • 63
  • 66
16

You can load the raw audio into an input stream and load it into a MediaPlayer as you would a normal stream:

InputStream ins = getResources().openRawResource(R.raw.example);

and then follow a streaming tutorial like pocketjourney

But this is overly complicated as you can just call

mp = MediaPlayer.create(counterstrikesb.this, R.raw.example);
stealthcopter
  • 13,964
  • 13
  • 65
  • 83
  • 14
    Relevant part of the documentation: "Note that since `prepare()` is called automatically in this method, you cannot change the audio stream type, audio session ID or audio attributes of the new MediaPlayer." – Dielson Sales Dec 24 '15 at 23:20
  • Link to pocketjourney in answer is dead. – Pang Feb 15 '18 at 05:18
  • 1
    This answer doesn't answer the actual question of the OP: you can not set an input stream in setDataSource... – SanThee Jul 28 '18 at 14:25