1

I am trying to play audio files stored in the assets directory, but before I even read a file I get the error "error occured java.io.FileNotFoundException: track.mp3". Here's how I read it:

AssetFileDescriptor afd = getAssets().openFd("track.mp3");

I read a lot of descriptions on the internet, but no success.

SimpleMan
  • 329
  • 7
  • 18
  • You could also store it in the raw directory under res, that way you can load it easier into the media player, since you can provide a res id. – Peterdk Dec 11 '11 at 21:23
  • Unfortunately I need to play a large number of files, so I don't really want to track every single one of them in my resources. – SimpleMan Dec 11 '11 at 21:51
  • For me it was case issue. File name was MP3 format in asset folder but I was using mp3 from code. By using exactly same name solve the issue. – 0xAliHn Jan 05 '20 at 00:48

4 Answers4

0

Android guidelines suggest for Audio use res/raw folder. So make sure that all audio are there and when you read you can use this method:

void playAudio(Context mContext, String sound){
    new AudioPlayer().play(mContext, mContext.getResources().getIdentifier(
            sound,"raw", mContext.getPackageName()));
}

And if you need something line audio player then take a look at MediaPlayer

Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60
0

Use this code

MediaPlayer mediaPlayer = new MediaPlayer();
            AssetFileDescriptor afd;
            try {
                afd = getAssets().openFd("1.mp3");
                mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                          Toast.makeText(LearnActivity.this, "Error Playing audio from Asset directory",Toast.LENGTH_SHORT).show();
            }

Otherwise, check if the file is in the right folder and the name is "track.mp3".

Mark Nashat
  • 668
  • 8
  • 9
0

I think this code should work for you:

AssetFileDescriptor afd = getAssets().openFd("track.mp3");

MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();

Otherwise, check if the file is in the right folder and the name is "track.mp3".

evilone
  • 22,410
  • 7
  • 80
  • 107
  • Well, as I said, before I even use MediaPlayer object, I get the FileNotFoundException. It is thrown after I open AssetFileDescriptor. – SimpleMan Dec 11 '11 at 21:49
  • This is the code path I'm using but it doesn't work: http://stackoverflow.com/questions/9124378/mp3-audio-in-the-android-assets-folder-fails-to-play-from-a-signed-and-zip-align – Timothy Lee Russell Feb 16 '12 at 05:50
0

Right-click your "track.mp3" file, with the "Refactor" > "Move" command, move your file to another directory (e.g. "res"). With this same command, move it back to your "assets" directory. For me, it works.