Android MediaPlayer Won't Play Different Sounds

Posted by cYn on Stack Overflow See other posts from Stack Overflow or by cYn
Published on 2012-12-02T23:01:50Z Indexed on 2012/12/02 23:03 UTC
Read the original article Hit count: 190

Filed under:

I'm making a simple app that plays a different sound according to its orientation. So if it's placed face down, a sound is played. If placed on its left side, a different sound is played. I'm having a hard time manipulating MediaPlayer correctly. My app runs fine. But it will only play one sound.

For example. When I first boot up my app and place my device facing up, a sound will play. If I change its orientation, the sound will pause. But it will not start a different sound in a different orientation. BUT, if I place the device back facing up, it resumes the sound that it paused.

I know I'm doing something wrong here, but I can't seem to figure it out the correct structure in using MediaPlayer and the program constantly calling it through onSensorChanged.

public class MainActivity extends Activity implements SensorEventListener{
    MediaPlayer mpAudioAttention;
    MediaPlayer mpAudioAssembly;
    MediaPlayer mpAudioRecall;
    MediaPlayer mpAudioRetreat;
    MediaPlayer mpAudioReveille;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    setContentView(R.layout.main);

    mpAudioAttention = MediaPlayer.create(this, R.raw.attention);
    mpAudioAssembly = MediaPlayer.create(this, R.raw.assembly);
    mpAudioRecall = MediaPlayer.create(this, R.raw.recall);
    mpAudioRetreat = MediaPlayer.create(this, R.raw.retreat);
    mpAudioReveille = MediaPlayer.create(this, R.raw.reveille);
}

public void onSensorChanged(SensorEvent event) {
    synchronized (this) {
        Log.d(tag, "onSensorChanged: " + event + ", z: " + event.values[0] + ", x: " + event.values[1] + ", y: " + event.values[2]);
        zViewO.setText("Orientation Z: " + event.values[0]);
        xViewO.setText("Orientation X: " + event.values[1]);
        yViewO.setText("Orientation Y: " + event.values[2]);
    }

    //face down
    if (event.values[2] > -11 && event.values[2] < -9){
        mpAudioRetreat.start();
    }
    else
        mpAudioRetreat.pause();

    //face up
    if (event.values[2] < 11 && event.values[2] > 9){
        mpAudioReveille.start();
    }
    else
        mpAudioReveille.pause();

    //standing
    if (event.values[0] > -10 && event.values[0] < -8){
        mpAudioAttention.start();
    }
    else
        mpAudioAttention.pause();

    //left sideways
    if (event.values[1] < 11 && event.values[1] > 9){
        mpAudioAssembly.start();
    }
    else
        mpAudioAssembly.pause();

    //right sideways
    if (event.values[1] > -11 && event.values[1] < -9){
        mpAudioRecall.start();
    }
    else
        mpAudioRecall.pause();

}

© Stack Overflow or respective owner

Related posts about android