David
David

Reputation: 21

Android audio looping

Although a seasoned developer, I'm new to Android, and am wanting to develop an app to loop between user defineable sections of audio recorded via Android's mic in.

I'm wanting as low latency as possible when the loop point is hit (i.e. miminal time to seek the start point of the section and resume playback).

I'm after some general recommendations such as:

audio file format
which classes should I be considering for playback (e.g. soundpool, media player etc)

Thanks for any advice

Dave

Upvotes: 2

Views: 6360

Answers (1)

FoamyGuy
FoamyGuy

Reputation: 46856

You can use Media player and an OnCompletetionListener like this:

    MediaPlayer mp;
    mp = MediaPlayer.create(getApplicationContext(), R.raw.yoursound);
    mp.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            mp.create(getApplicationContext(), R.raw.nextsound);
            mp.prepare();
            mp.start();
        }

    });
    mp.prepare();
    mp.start();

As for sound file types I've never noticed much of a difference between any of them. I tend to stick with .mp3 or .ogg though just because the file size tends to be smaller for those than for .wav.

Edit: Ahh I see, If you are wanting to play the whole audio file over and over you just need to call setLooping(true) like this:

    MediaPlayer mp;
    mp = MediaPlayer.create(getApplicationContext(), R.raw.yoursound);
    mp.setLooping(true);
    mp.prepare();
    mp.start();

If you are trying to play the full audio file once, then loop some small section of it over and over you can use the .seekTo() method inside the completionlistener like this:

    MediaPlayer mp;
    mp = MediaPlayer.create(getApplicationContext(), R.raw.yoursound);
    mp.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(getApplicationContext(), R.raw.yoursound);
            mp.seekTo(3000); //3 seconds in
            mp.prepare();
            mp.start();
        }

    });
    mp.prepare();
    mp.start();

Upvotes: 6

Related Questions