Sai
Sai

Reputation: 15718

Issue with looping an audio file

How can i get the value of repetitions completed from mp.setLooping(true). I can use OnCompletionListener to get number of repetitions, but it produces 1sec delay between looping, which is annoying in a music oriented app. OnCompletionListener looping is not smooth asmp.setLooping(true).

Any suggestions ? Thank in advance.

Code with 1sec delay or gap between looping:

public class MainActivity extends Activity {
MediaPlayer mp1;
Button play;
int maxCount=10,n=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    play = (Button) findViewById(R.id.button1);
    mp = MediaPlayer.create(MainActivity.this, R.raw.soundfile);
    play.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mpplay();
        }
    });

}
private void mpplay() {
    mp1.start();
    mp1.setOnCompletionListener(new OnCompletionListener() {        
        @Override
        public void onCompletion(MediaPlayer mp1) {
            if (n <= maxCount) {
                mp1.start();
                n++;
                if (n >= maxCount) {
                    n = 1;
                    mp1.stop();
                }
            }
        }
    });
}}

Upvotes: 0

Views: 1249

Answers (1)

eski
eski

Reputation: 7915

Try this out:

MediaPlayer mp1;
double play_times = 10;
int sound_length;
Handler handler;
boolean sound_playing = false;
int times_played = 0;

public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.home);
    handler = new Handler();
    mp1 = MediaPlayer.create(this, R.raw.soundfile);
    sound_length = mp1.getDuration();
    mpplay();

}
private void mpplay() {
    times_played = 0;
    mp1.setLooping(true);
    mp1.start();
    sound_playing = true;
    handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));
    handler.postDelayed(counter, sound_length);

}
private Runnable loop_stopper = new Runnable() {
    public void run() {
        sound_playing = false;
        mp1.setLooping(false);
    }
};
private Runnable counter = new Runnable() {
    public void run() {
        if (sound_playing) {
            times_played++;
            handler.postDelayed(counter, sound_length);
        }
    }
};

handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));

This line will stop the looping halfway through the last desired loop. Since this just means it won't continue looping, the sound file will still be fully played on the last repeat.

Upvotes: 3

Related Questions