Kyeongsik Jason Kim
Kyeongsik Jason Kim

Reputation: 117

Playing Audio using AssetFileDescriptor does not work

Now I'm working on Audio Player, using AssetFileDescriptor. But The song(R.raw.music3) won't play without error,, I can't find out what I did wrong,, please help me with this.

private void playAudio_UsingDescriptor() throws Exception{
    AssetFileDescriptor fileDesc=getResources().openRawResourceFd(R.raw.music3);

        sound2=new MediaPlayer();
        sound2.setAudioStreamType(AudioManager.STREAM_MUSIC);
        sound2.setDataSource(fileDesc.getFileDescriptor());
        fileDesc.close();
        sound2.prepareAsync();
        sound2.start();

}
try {
     playAudio_UsingDescriptor();  
     }
     catch (Exception e){
                        sound2.start();
                        }

Upvotes: 2

Views: 1447

Answers (1)

Mike M.
Mike M.

Reputation: 39191

Since you already have your audio file in the /res/raw directory, try using the following to initialize your MediaPlayer, instead of using an AssetFileDescriptor:

sound2 = MediaPlayer.create(MainActivity.this, R.raw.music3);

Replace MainActivity.this with the applicable Context object.

Alternatively:

sound2 = new MediaPlayer();
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.music3);

try
{           
    sound2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    afd.close();
    sound2.prepare();           
}
catch (IOException e)
{}

sound2.start();

Upvotes: 4

Related Questions