1

I'm trying to play an mp3 file from the assets directory, but when I start it up with the MediaPlayer, something completely different plays. Here's the code:

String mp3File = "dir/a/music.mp3";  //the path here is file:///android_asset/dir/a/music.mp3;
AssetManager assetMan = getAssets();
MediaPlayer media = new MediaPlayer();
FileInputStream mp3Stream = assetMan.openFd(mp3File).createInputStream();
media.setDataSource(mp3Stream.getFD());
media.prepare();
media.start();

Instead of playing mp3File, it seems to play a bunch of other files that reside in the assets directory. Any ideas?

Jays
  • 145
  • 3
  • 8
  • What do you mean plays a bunch of other files? Does it just play each one at the same time? One after the other? Have you set some debug points to see exactly what the datasource of the MediaPlayer is set too? – Jack Aug 26 '11 at 03:54
  • mediaplayer.setDataSource("file:///android_asset/ – Android Aug 26 '11 at 06:59
  • possible duplicate of [Play audio file from the assets directory](http://stackoverflow.com/questions/3289038/play-audio-file-from-the-assets-directory) – Matt Gibson Jan 12 '12 at 22:23

2 Answers2

4

Use this way it is very useful function :)

    public void playBeep() {
    try {

        if (m.isPlaying()) {
            m.stop();
            m.release();
            m = new MediaPlayer();
        }
        AssetFileDescriptor descriptor = getAssets().openFd("mp3 name.mp3");
        m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        m.prepare();
        m.setVolume(1f, 1f);
        m.setLooping(true);
        m.start();
    } catch (Exception e) {
    }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150
1
   MediaPlayer mp = new MediaPlayer();     
     AssetFileDescriptor descriptor;
   descriptor = getAssets().openFd( "filename.mp3" );
    mp.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(),  descriptor.getLength() );
    descriptor.close();
    mp.prepare();
   mp.start();

put your mp3 in the assets folder. you can refer this link also play-audio-file-from-the-assets-directory
and this also android-problem-playing-sounds-from-assets-folder

Community
  • 1
  • 1
Android
  • 8,995
  • 9
  • 67
  • 108