简体   繁体   中英

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();

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);

在你打电话准备之前你不能寻求,我不确定你是否可以在实际调用MediaPlayer.play()之前做到这一点,说实话你需要检查它,但肯定准备先行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM