Android ToggleButton Tutorial 2 – Adding MediaPlayer func.

Now there is this nice small Button from the first article – what to do with it???

You can add media-playback functionality – thats what’s coverd in the next section

for a very simple mediaplayer which only takes a single mp3 and starts playback on click,
you only need a few things.

Start by adding a Field for your MediaPlayer

private MediaPlayer mp;

then create the MediaPlayer for a given resource id inside the onCreate method.

mp = MediaPlayer.create(getBaseContext(), R.raw.sound_file_1);

you can add the mp3 by drag and drop one to your eclipse project folder in yourproject/res/raw (if raw does not exist simply create it)!

now add a OnCheckedChangedListener to the ToggleButton wich is a subclass of CompundButton.

CompoundButton btn = (ToggleButton) findViewById(R.id.ToggleButton);
btn.setOnCheckedChangeListener(this);

and last but not least create a OnCheckedChanged method do specify what to do when the ToggleButton is clicked/cheked.

here’s the full source:

import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ToggleButtonTest extends Activity implements
OnCheckedChangeListener {

private MediaPlayer mp;

public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

mp = MediaPlayer.create(getBaseContext(), R.raw.sound_file_1);

CompoundButton btn = (ToggleButton) findViewById(R.id.ToggleButton);
btn.setOnCheckedChangeListener(this);

}

@Override
public void onCheckedChanged(CompoundButton btn, boolean isChecked) {

if (btn.isChecked()) {
mp.start();
} else {
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

~ von w3world - Februar 12, 2009.

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s

 
%d Bloggern gefällt das: