Hello everyone,

I have an application with 2 buttons. Click button button_testWav will
play wav audio, and click button button_quit will call method
quit(View view) to exit the application (this is defined in layout XML
file). One interesting thing is after I click button_testWav, audio
starts playing. Then I press key "back" on my Droid X, audio still
plays in background.
I would like to know how to control MediaPlayer again after I launch
the application later, so that I won't have too many copies open?
Thanks!

Below is the test code:
package com.MediaPlayerTest;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MediaPlayerTest extends Activity
{
    private static final String TAG = "MediaPlayerTest";
    private static MediaPlayer mp;

    private void playMusic(String pathToFile)
    {
        mp.reset();
        try
        {
            mp.setDataSource(pathToFile);
        } catch (IllegalArgumentException e)
        {
            Log.d(TAG, "IllegalArgumentException");
            e.printStackTrace();
        } catch (IllegalStateException e)
        {
            Log.d(TAG, "IllegalStateException in setDataSource");
            e.printStackTrace();
        } catch (IOException e)
        {
            Log.d(TAG, "IOException  in setDataSource");
            e.printStackTrace();
        }
        try
        {
            mp.prepare();
        } catch (IllegalStateException e)
        {
            Log.d(TAG, "IllegalStateException in prepare");
            e.printStackTrace();
        } catch (IOException e)
        {
            Log.d(TAG, "IOException in prepare");
            Toast.makeText(this, "Couldn't open audio file.",
Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        mp.start();
    }

    public void quit(View view)
    {
        mp.stop();
        mp.release();
        this.finish();
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Log.d(TAG, "onCreate");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mp = new MediaPlayer();

        final Button button_testWav = (Button)
findViewById(R.id.button_testWav);
        button_testWav.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                playMusic("/sdcard/res/test.wav");
            }
        });
    }
}

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to