Setting data source to an raw ID in MediaPlayer

前端 未结 3 990
眼角桃花
眼角桃花 2020-12-01 13:53

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

相关标签:
3条回答
  • 2020-12-01 14:17

    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));
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-01 14:30

    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.

    0 讨论(0)
提交回复
热议问题