简体   繁体   中英

How to loop audio from one second to another

I'm making an application with sounds that I want to loop.

The problem is that audios have a kind of fade in and fade out that every time it is played with mediaPlayer.setLooping(true); they make the loop sound very bad, because you hear it perfectly when it ends and when it starts again.

I would like to be able to play those audios from one particular second to another, for example to be able to loop from the second 00:00:04 to the second 00:00:14 and thus not hear the fade in and fade out.

At the moment I'm using this code to play the audios. Then in the button, I make the call that you see next

    public void playAudio(int audioId)
    {
        // stop the previous playing audio
        if(mMediaPlayer != null && mMediaPlayer.isPlaying())
        {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

        mMediaPlayer = MediaPlayer.create(this, audioId);

        mMediaPlayer.start();
        mMediaPlayer.setLooping(true);

    }

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 

            playAudio(R.raw.sound1);

            }
        });

Create a method called startPosition(int initialTime) which will seek mediaPlayer position before start() method

private void startPosition(int initialTime){
    mMediaPlayer.seekTo(initialTime);    //time in millisecond, e.g 4sec = 4000
}

call this method before mMediaPlayer.start() method.

Now create a thread which will run endlessly and seek your mediaplayer position back to initial on upper limit reached. Edit Replace your playAudio() method with the below and change upperTimerLimit with specific value eg 14000 (14 second).

public void playAudio(int audioId)
{
    // stop the previous playing audio
    if(mMediaPlayer != null && mMediaPlayer.isPlaying())
    {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    mMediaPlayer = MediaPlayer.create(this, audioId);

    mMediaPlayer.start();
    new Thread(new Runnable() { 
        public void run(){        
            while(true){
                if(mMediaPlayer.getCurrentPosition()-UpperTimeLimit >=0){ //UpperTimeLimit should be in milliseconds. UpperTimerLimit is the specific second after which player should start again the sound.
                    startPosition(initialTime);    //Call the startPosition(int initialTime)
                }
        }
    }).start();
}

Create the thread right after mMediaPlayer.start() There is no need of mMediaPlayer.setLooping(true); in your playAudio() method.

Hope this will work.

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