HK.avdalyan
HK.avdalyan

Reputation: 734

Android Playing audio file (.wav)

Need to play some .wav file but only some part of it (from start). For example I have test.wav file and it is 10 seconds I want to play only 0-5 seconds. I try to use seekTo method but it doesn't help my app was crashed.

    AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.test);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
    mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
    mMediaPlayer.setOnCompletionListener(mMediaPlayerCompletionListener);
    mMediaPlayer.seekTo(5000);
    mMediaPlayer.prepare();

Upvotes: 0

Views: 312

Answers (2)

Melquiades
Melquiades

Reputation: 8598

You could just stop playing after set amount of time (5 sec in your case). There are many ways to do that, one could be:

final Handler handler = new Handler();

//create a runnable that will be called to stop playback
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //stop playback, make sure mMediaPlayer is declared as a field
        //in the class where it's used
        mMediaPlayer.stop();
    }
};

//post a job for handler do be done in 5 seconds
handler.postDelayed(runnable, 5 * 1000);

Upvotes: 2

Maciej Boguta
Maciej Boguta

Reputation: 1374

you can't seek before you call prepare, i am not sure whether you can do that before actually calling MediaPlayer.play() to be honest you need to check that up but for sure prepare goes first.

Upvotes: 0

Related Questions