masmic
masmic

Reputation: 3564

Play sound continuosly until user stops

I'm developing a test app that when the automated testing process finishes an alarm sound is played to notify the operator.

This sound is a 3secs duration alarm ringtone, and I need to be played in loop until the user touches the phone screen.

This is the way I implement the mediaplayer:

mp = MediaPlayer.create(MainActivity.this, R.raw.alarm);
    try {
        mp.prepare();
        mp.setLooping(true);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.start();
    }

I have defined the mp.setLooping that should make the sound play continuosly, but it doesn't.

Then, to stop the sound touching the screen:

@Override
public boolean onTouchEvent (MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        /*If sound is playing, stops*/
        if (mp.isPlaying()) {
            mp.stop();
        }
        return true;
    }
    return super.onTouchEvent(event);
}

So if mp.setLooping is not working, how should I make the sound play continuosly?

Upvotes: 0

Views: 560

Answers (2)

Malki Bulathsinhala
Malki Bulathsinhala

Reputation: 1

mp = MediaPlayer.create(MainActivity.this, R.raw.alarm);
mp.start();
mp.setLooping(true);

Upvotes: -1

Mike M.
Mike M.

Reputation: 39191

When you instantiate a MediaPlayer with create(), it is returned in a prepared state and you must not call prepare() on it. In your case, this is throwing an Exception, and therefore mp.setLooping(true) isn't being called.

Upvotes: 5

Related Questions