Mega Code Archive

 
Categories / Android / UI
 

Using Button to control MediaPlayer

package app.test; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; public class Test extends Activity implements     OnCompletionListener, OnTouchListener, OnClickListener {   MediaPlayer mediaPlayer;   View theView;   Button stopButton, startButton;   int position = 0;   @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);     stopButton = (Button) this.findViewById(R.id.StopButton);     startButton = (Button) this.findViewById(R.id.StartButton);     startButton.setOnClickListener(this);     stopButton.setOnClickListener(this);     theView = this.findViewById(R.id.theview);     theView.setOnTouchListener(this);     mediaPlayer = MediaPlayer.create(this, R.raw.a);//raw/a.mp3     mediaPlayer.setOnCompletionListener(this);     mediaPlayer.start();   }   public void onCompletion(MediaPlayer mp) {     mediaPlayer.start();     mediaPlayer.seekTo(position);   }   public boolean onTouch(View v, MotionEvent me) {     if (me.getAction() == MotionEvent.ACTION_MOVE) {       if (mediaPlayer.isPlaying()) {         position = (int) (me.getX() * mediaPlayer.getDuration() / theView             .getWidth());         Log.v("SEEK", "" + position);         mediaPlayer.seekTo(position);       }     }     return true;   }   public void onClick(View v) {     if (v == stopButton) {       mediaPlayer.pause();     } else if (v == startButton) {       mediaPlayer.start();     }   } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="vertical"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     > <Button android:text="Start" android:id="@+id/StartButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="Stop" android:id="@+id/StopButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <View android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/theview" /> </LinearLayout>