Tuesday, July 12, 2011

A simple exercise to play MIDI audio using MediaPlayer

Put a MIDI file into the res/raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class. "midi_sound.mid" in my exercise.





LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
Button
android:id="@+id/play"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PLAY -"
Button
android:id="@+id/pause"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- PAUSE -"
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidAudioPlayer extends Activity {

MediaPlayer mediaPlayer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mediaPlayer = MediaPlayer.create(this, R.raw.midi_sound);

    Button buttonPlay = (Button)findViewById(R.id.play);
    Button buttonPause = (Button)findViewById(R.id.pause);
    buttonPlay.setOnClickListener(buttonPlayOnClickListener);
    buttonPause.setOnClickListener(buttonPauseOnClickListener);
}

Button.OnClickListener buttonPlayOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying()){
 mediaPlayer.start();
 Toast.makeText(AndroidAudioPlayer.this,
   "mediaPlayer.start()",
   Toast.LENGTH_LONG).show();
}
}
};

Button.OnClickListener buttonPauseOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer.isPlaying()){
 mediaPlayer.pause();
 Toast.makeText(AndroidAudioPlayer.this,
   "mediaPlayer.pause()",
   Toast.LENGTH_LONG).show();
}
}
};

}

No comments:

Post a Comment