Download MediaPlayer from Uri in the context of assets

I have an audio file in my resources directory. assets / audio / dance.mp3.

If I ran context.getAssets (). list ("audio"); he appears.

But when I try to use MediaPlayer.create (context, uri), it always fails and returns null.

none of this works

private void tryLoad(String path,Context context)
{
    Uri uri = Uri.parse(path);
    this.audioPlayer =  MediaPlayer.create(context,uri);
    if (this.audioPlayer == null)
    {
        Log.d(TAG, "loadAudio: audioPlayer is null. current assets"+ uri.toString()) ;
    }
    else
    {
        Log.d(TAG, "loadAudio: WORKED"+ uri.toString()) ;
    }

}
public void loadAudio(Context context)
{
    if (this.audioPlayer != null)
        return;
    if (this.audioFile != null && this.audioFile.length() >0)
    {
        try 
        {
            tryLoad("/dance.mp3",context);
            tryLoad("dance.mp3",context);
            tryLoad("audio/dance.mp3",context);
            tryLoad("/audio/dance.mp3",context);
            tryLoad("assets/audio/dance.mp3",context);
            tryLoad("/assets/audio/dance.mp3",context);
            tryLoad("\\dance.mp3",context);
            tryLoad("dance.mp3",context);
            tryLoad("audio\\dance.mp3",context);
            tryLoad("\\audio\\dance.mp3",context);
            tryLoad("assets\\audio\\dance.mp3",context);
            tryLoad("\\assets\\audio\\dance.mp3",context);
        }   
        catch (Exception e)
        {
            Log.d(TAG, "loadAudio exception: " + e.getMessage());
        }
    }
}
+5
source share
4 answers

, , MediaPlayer URI, URI . MediaPlayer MediaPlayer.setDataSource(FileDescriptor). FileDescriptor AssetManager.openFd(), AssetFileDescriptor.getFileDescriptor() .

, . , .

+3

you cannot call mp.setDataSource (afd.getFileDescriptor ()); in the asset file, since it will play all assets. Instead, follow the solution in this thread: Play an audio file from the asset catalog

+1
source

You need to put the file in a folder res/rawand then upload it with:

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);

From: Android Documentation

0
source

All Articles