Android Tutorial - Media : MediaPlayer

 Using MediaPlayer to play MP3 file

   
package app.Test;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;

public class appTest extends Activity {
     private MediaPlayer up;

     
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        up = MediaPlayer.create(this, R.raw.up);
     }
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
        MediaPlayer mp;
        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_UP:
           mp = up;
           break;
        default:
           return super.onKeyDown(keyCode, event);
        }
        mp.seekTo(0); 
        mp.start();
        return true;
     }
}

MediaPlayer and Text to Speech

   
package app.test;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Test extends Activity implements OnInitListener {
  private EditText words = null;
  private Button speakBtn = null;
  private EditText filename = null;
  private Button recordBtn = null;
  private Button playBtn = null;
  private EditText useWith = null;
  private Button assocBtn = null;
  private String soundFilename = null;
  private File soundFile = null;
    private static final int REQ_TTS_STATUS_CHECK = 0;
  private static final String TAG = "TTS Demo";
    private TextToSpeech mTts = null;
    private MediaPlayer player = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        words = (EditText)findViewById(R.id.wordsToSpeak);
        filename = (EditText)findViewById(R.id.filename);
        useWith = (EditText)findViewById(R.id.realText);

        speakBtn = (Button)findViewById(R.id.speakBtn);
        recordBtn = (Button)findViewById(R.id.recordBtn);
        playBtn = (Button)findViewById(R.id.playBtn);
        assocBtn = (Button)findViewById(R.id.assocBtn);
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
    }
    
    public void doButton(View view) {
      switch(view.getId()) {
      case R.id.speakBtn:
          mTts.speak(words.getText().toString(), TextToSpeech.QUEUE_ADD, null);
          break;
      case R.id.recordBtn:
        soundFilename = filename.getText().toString();
        soundFile = new File(soundFilename);
        if (soundFile.exists())
          soundFile.delete();

          if(mTts.synthesizeToFile(words.getText().toString(), null, soundFilename)== TextToSpeech.SUCCESS) {
            Toast.makeText(getBaseContext(),"Sound file created",Toast.LENGTH_SHORT).show();
            playBtn.setEnabled(true);
            assocBtn.setEnabled(true);
          }
          else {
            Toast.makeText(getBaseContext(),"Oops! Sound file not created",Toast.LENGTH_SHORT).show();
          }
          break;
      case R.id.playBtn:
        try {
            player = new MediaPlayer();
                player.setDataSource(soundFilename);
          player.prepare();
            player.start();
        }
        catch(Exception e) {
            Toast.makeText(getBaseContext(),"Hmmmmm. Can't play file",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        break;
      case R.id.assocBtn:
        mTts.addSpeech(useWith.getText().toString(), soundFilename);
          Toast.makeText(getBaseContext(),"Associated!",Toast.LENGTH_SHORT).show();
          break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_TTS_STATUS_CHECK) {
            switch (resultCode) {
            case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
                mTts = new TextToSpeech(this, this);
                Log.v(TAG, "Pico is installed okay");
                break;
            case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
            case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
            case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
                Intent installIntent = new Intent();
                installIntent.setAction(
                    TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
                break;
            case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
            default:
                Log.e(TAG, "Got a failure. TTS apparently not available");
            }
        }
    }

  public void onInit(int status) {
    if( status == TextToSpeech.SUCCESS) {
      speakBtn.setEnabled(true);
      recordBtn.setEnabled(true);
    }
  }
  @Override
  public void onPause()
  {
    super.onPause();
        if(player != null) {
          player.stop();
        }
    if( mTts != null)
      mTts.stop();
  }

  @Override
    public void onDestroy()
  {
        super.onDestroy();
        if(player != null) {
          player.release();
        }
    if( mTts != null) {
      mTts.shutdown();
    }
    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <EditText android:id="@+id/wordsToSpeak"
    android:text="Dohn Keyhotay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

  <Button android:id="@+id/speakBtn"
    android:text="Speak"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="doButton"
  android:enabled="false" />

  <TextView android:id="@+id/filenameLabel"
    android:text="Filename:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

  <EditText android:id="@+id/filename"
    android:text="/sdcard/donquixote.wav"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

  <Button android:id="@+id/recordBtn"
    android:text="Record"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="doButton"
  android:enabled="false" />

  <Button android:id="@+id/playBtn"
    android:text="Play"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="doButton"
  android:enabled="false" />

  <TextView android:id="@+id/useWithLabel"
    android:text="Use with:"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

  <EditText android:id="@+id/realText"
    android:text="Don Quixote"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

  <Button android:id="@+id/assocBtn"
    android:text="Associate"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="doButton"
  android:enabled="false" />

</LinearLayout>

Load mp3 file with MediaPlayer and play

   
package app.test;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;

public class Test extends Activity implements OnCompletionListener {

  MediaPlayer mediaPlayer;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void onCompletion(MediaPlayer mp) {
    mediaPlayer.start();
  }

  public void onStart() {
    super.onStart();
    mediaPlayer = MediaPlayer.create(this, R.raw.s);//raw/s.mp3
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.start();
  }

  public void onStop() {
    super.onStop();
    // Log.v("CustomAudioPlayer","onStop Called");
    mediaPlayer.stop();
    mediaPlayer.release();
  }

}

Call prepare for MediaPlayer before starting

   

package app.test;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;

public class Test extends Activity {

  MediaPlayer mediaPlayer;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mediaPlayer = new MediaPlayer();

    try {
      mediaPlayer.setDataSource("http://yourHost.com/a.mp3");
      mediaPlayer.prepare();
      mediaPlayer.start();
    } catch (IOException e) {
      Log.v("AUDIOHTTPPLAYER", e.getMessage());
    }
  }
}

Set URL data source for MediaPlayer

   

package app.test;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;

public class Test extends Activity {

  MediaPlayer mediaPlayer;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mediaPlayer = new MediaPlayer();

    try {
      mediaPlayer.setDataSource("http://yourHost.com/a.mp3");
      mediaPlayer.prepare();
      mediaPlayer.start();
    } catch (IOException e) {
      Log.v("AUDIOHTTPPLAYER", e.getMessage());
    }
  }
}
Audio MediaPlayer Demo
package com.example.android.apis.media;

import com.example.android.apis.R;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Equalizer;
import android.media.audiofx.Visualizer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;

public class AudioFxDemo extends Activity {
    private static final String TAG = "AudioFxDemo";

    private static final float VISUALIZER_HEIGHT_DIP = 50f;

    private MediaPlayer mMediaPlayer;
    private Visualizer mVisualizer;
    private Equalizer mEqualizer;

    private LinearLayout mLinearLayout;
    private VisualizerView mVisualizerView;
    private TextView mStatusTextView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        mStatusTextView = new TextView(this);

        mLinearLayout = new LinearLayout(this);
        mLinearLayout.setOrientation(LinearLayout.VERTICAL);
        mLinearLayout.addView(mStatusTextView);

        setContentView(mLinearLayout);

        // Create the MediaPlayer
        mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);//test_cbr.mp3
        Log.d(TAG, "MediaPlayer audio session ID: " + mMediaPlayer.getAudioSessionId());

        setupVisualizerFxAndUI();
        setupEqualizerFxAndUI();

        // Make sure the visualizer is enabled only when you actually want to receive data, and
        // when it makes sense to receive data.
        mVisualizer.setEnabled(true);

        // When the stream ends, we don't need to collect any more data. We don't do this in
        // setupVisualizerFxAndUI because we likely want to have more, non-Visualizer related code
        // in this callback.
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mediaPlayer) {
                mVisualizer.setEnabled(false);
            }
        });

        mMediaPlayer.start();
        mStatusTextView.setText("Playing audio...");
    }

    private void setupEqualizerFxAndUI() {
        // Create the Equalizer object (an AudioEffect subclass) and attach it to our media player,
        // with a default priority (0).
        mEqualizer = new Equalizer(0, mMediaPlayer.getAudioSessionId());
        mEqualizer.setEnabled(true);

        TextView eqTextView = new TextView(this);
        eqTextView.setText("Equalizer:");
        mLinearLayout.addView(eqTextView);

        short bands = mEqualizer.getNumberOfBands();

        final short minEQLevel = mEqualizer.getBandLevelRange()[0];
        final short maxEQLevel = mEqualizer.getBandLevelRange()[1];

        for (short i = 0; i < bands; i++) {
            final short band = i;

            TextView freqTextView = new TextView(this);
            freqTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            freqTextView.setGravity(Gravity.CENTER_HORIZONTAL);
            freqTextView.setText((mEqualizer.getCenterFreq(band) / 1000) + " Hz");
            mLinearLayout.addView(freqTextView);

            LinearLayout row = new LinearLayout(this);
            row.setOrientation(LinearLayout.HORIZONTAL);

            TextView minDbTextView = new TextView(this);
            minDbTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            minDbTextView.setText((minEQLevel / 100) + " dB");

            TextView maxDbTextView = new TextView(this);
            maxDbTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            maxDbTextView.setText((maxEQLevel / 100) + " dB");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.weight = 1;
            SeekBar bar = new SeekBar(this);
            bar.setLayoutParams(layoutParams);
            bar.setMax(maxEQLevel - minEQLevel);
            bar.setProgress(mEqualizer.getBandLevel(band));

            bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress,
                        boolean fromUser) {
                    mEqualizer.setBandLevel(band, (short) (progress + minEQLevel));
                }

                public void onStartTrackingTouch(SeekBar seekBar) {}
                public void onStopTrackingTouch(SeekBar seekBar) {}
            });

            row.addView(minDbTextView);
            row.addView(bar);
            row.addView(maxDbTextView);

            mLinearLayout.addView(row);
        }
    }

    private void setupVisualizerFxAndUI() {
        // Create a VisualizerView (defined below), which will render the simplified audio
        // wave form to a Canvas.
        mVisualizerView = new VisualizerView(this);
        mVisualizerView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density)));
        mLinearLayout.addView(mVisualizerView);

        // Create the Visualizer object and attach it to our media player.
        mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
        mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
        mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
            public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
                    int samplingRate) {
                mVisualizerView.updateVisualizer(bytes);
            }

            public void onFftDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) {}
        }, Visualizer.getMaxCaptureRate() / 2, true, false);
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (isFinishing() && mMediaPlayer != null) {
            mVisualizer.release();
            mEqualizer.release();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}

/**
 * A simple class that draws waveform data received from a
 * {@link Visualizer.OnDataCaptureListener#onWaveFormDataCapture }
 */
class VisualizerView extends View {
    private byte[] mBytes;
    private float[] mPoints;
    private Rect mRect = new Rect();

    private Paint mForePaint = new Paint();

    public VisualizerView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mBytes = null;

        mForePaint.setStrokeWidth(1f);
        mForePaint.setAntiAlias(true);
        mForePaint.setColor(Color.rgb(0, 128, 255));
    }

    public void updateVisualizer(byte[] bytes) {
        mBytes = bytes;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mBytes == null) {
            return;
        }

        if (mPoints == null || mPoints.length < mBytes.length * 4) {
            mPoints = new float[mBytes.length * 4];
        }

        mRect.set(0, 0, getWidth(), getHeight());

        for (int i = 0; i < mBytes.length - 1; i++) {
            mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
            mPoints[i * 4 + 1] = mRect.height() / 2
                    + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
            mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
            mPoints[i * 4 + 3] = mRect.height() / 2
                    + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2) / 128;
        }

        canvas.drawLines(mPoints, mForePaint);
    }
}
//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="match_parent"
    android:layout_height="match_parent"
    >
    
    <VideoView 
        android:id="@+id/surface_view" 
        android:layout_width="320px"
        android:layout_height="240px"
    />
    
</LinearLayout>

Using MediaPlayer to play Video and Audio

package com.example.android.apis.media;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

class MediaPlayerDemo_Audio extends Activity {

  private static final String TAG = "MediaPlayerDemo";
  private MediaPlayer mMediaPlayer;
  private static final String MEDIA = "media";
  private static final int LOCAL_AUDIO = 1;
  private static final int STREAM_AUDIO = 2;
  private static final int RESOURCES_AUDIO = 3;
  private static final int LOCAL_VIDEO = 4;
  private static final int STREAM_VIDEO = 5;
  private String path;

  private TextView tx;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    tx = new TextView(this);
    setContentView(tx);
    Bundle extras = getIntent().getExtras();
    playAudio(extras.getInt(MEDIA));
  }

  private void playAudio(Integer media) {
    try {
      switch (media) {
      case LOCAL_AUDIO:
        /**
         * TODO: Set the path variable to a local audio file path.
         */
        path = "";
        if (path == "") {
          // Tell the user to provide an audio file URL.
          Toast.makeText(
              MediaPlayerDemo_Audio.this,
              "Please edit MediaPlayer_Audio Activity, "
                  + "and set the path variable to your audio file path."
                  + " Your audio file must be stored on sdcard.",
              Toast.LENGTH_LONG).show();

        }
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(path);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        break;
      case RESOURCES_AUDIO:
        /**
         * TODO: Upload a audio file to res/raw folder and provide its
         * resid in MediaPlayer.create() method.
         */
        mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);//test_cbr.mp3
        mMediaPlayer.start();

      }
      tx.setText("Playing audio...");

    } catch (Exception e) {
      Log.e(TAG, "error: " + e.getMessage(), e);
    }

  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    // TODO Auto-generated method stub
    if (mMediaPlayer != null) {
      mMediaPlayer.release();
      mMediaPlayer = null;
    }

  }
}

class MediaPlayerDemo_Video extends Activity implements
    OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener,
    OnVideoSizeChangedListener, SurfaceHolder.Callback {

  private static final String TAG = "MediaPlayerDemo";
  private int mVideoWidth;
  private int mVideoHeight;
  private MediaPlayer mMediaPlayer;
  private SurfaceView mPreview;
  private SurfaceHolder holder;
  private String path;
  private Bundle extras;
  private static final String MEDIA = "media";
  private static final int LOCAL_AUDIO = 1;
  private static final int STREAM_AUDIO = 2;
  private static final int RESOURCES_AUDIO = 3;
  private static final int LOCAL_VIDEO = 4;
  private static final int STREAM_VIDEO = 5;
  private boolean mIsVideoSizeKnown = false;
  private boolean mIsVideoReadyToBePlayed = false;

  /**
   * 
   * Called when the activity is first created.
   */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.row);
    mPreview = (SurfaceView) findViewById(R.id.surface);
    holder = mPreview.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    extras = getIntent().getExtras();

  }

  private void playVideo(Integer Media) {
    doCleanUp();
    try {

      switch (Media) {
      case LOCAL_VIDEO:
        /*
         * TODO: Set the path variable to a local media file path.
         */
        path = "";
        if (path == "") {
          // Tell the user to provide a media file URL.
          Toast.makeText(
              MediaPlayerDemo_Video.this,
              "Please edit MediaPlayerDemo_Video Activity, "
                  + "and set the path variable to your media file path."
                  + " Your media file must be stored on sdcard.",
              Toast.LENGTH_LONG).show();

        }
        break;
      case STREAM_VIDEO:
        /*
         * TODO: Set path variable to progressive streamable mp4 or 3gpp
         * format URL. Http protocol should be used. Mediaplayer can
         * only play "progressive streamable contents" which basically
         * means: 1. the movie atom has to precede all the media data
         * atoms. 2. The clip has to be reasonably interleaved.
         */
        path = "";
        if (path == "") {
          // Tell the user to provide a media file URL.
          Toast.makeText(
              MediaPlayerDemo_Video.this,
              "Please edit MediaPlayerDemo_Video Activity,"
                  + " and set the path variable to your media file URL.",
              Toast.LENGTH_LONG).show();

        }

        break;

      }

      // Create a new media player and set the listeners
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.setDisplay(holder);
      mMediaPlayer.prepare();
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    } catch (Exception e) {
      Log.e(TAG, "error: " + e.getMessage(), e);
    }
  }

  public void onBufferingUpdate(MediaPlayer arg0, int percent) {
    Log.d(TAG, "onBufferingUpdate percent:" + percent);

  }

  public void onCompletion(MediaPlayer arg0) {
    Log.d(TAG, "onCompletion called");
  }

  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    Log.v(TAG, "onVideoSizeChanged called");
    if (width == 0 || height == 0) {
      Log.e(TAG, "invalid video width(" + width + ") or height(" + height
          + ")");
      return;
    }
    mIsVideoSizeKnown = true;
    mVideoWidth = width;
    mVideoHeight = height;
    if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
      startVideoPlayback();
    }
  }

  public void onPrepared(MediaPlayer mediaplayer) {
    Log.d(TAG, "onPrepared called");
    mIsVideoReadyToBePlayed = true;
    if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
      startVideoPlayback();
    }
  }

  public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
    Log.d(TAG, "surfaceChanged called");

  }

  public void surfaceDestroyed(SurfaceHolder surfaceholder) {
    Log.d(TAG, "surfaceDestroyed called");
  }

  public void surfaceCreated(SurfaceHolder holder) {
    Log.d(TAG, "surfaceCreated called");
    playVideo(extras.getInt(MEDIA));

  }

  @Override
  protected void onPause() {
    super.onPause();
    releaseMediaPlayer();
    doCleanUp();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    releaseMediaPlayer();
    doCleanUp();
  }

  private void releaseMediaPlayer() {
    if (mMediaPlayer != null) {
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
  }

  private void doCleanUp() {
    mVideoWidth = 0;
    mVideoHeight = 0;
    mIsVideoReadyToBePlayed = false;
    mIsVideoSizeKnown = false;
  }

  private void startVideoPlayback() {
    Log.v(TAG, "startVideoPlayback");
    holder.setFixedSize(mVideoWidth, mVideoHeight);
    mMediaPlayer.start();
  }
}

public class Test extends Activity {
  private Button mlocalvideo;
  private Button mresourcesvideo;
  private Button mstreamvideo;
  private Button mlocalaudio;
  private Button mresourcesaudio;
  private Button mstreamaudio;
  private static final String MEDIA = "media";
  private static final int LOCAL_AUDIO = 1;
  private static final int STREAM_AUDIO = 2;
  private static final int RESOURCES_AUDIO = 3;
  private static final int LOCAL_VIDEO = 4;
  private static final int STREAM_VIDEO = 5;
  private static final int RESOURCES_VIDEO = 6;

  @Override
  protected void onCreate(Bundle icicle) {
    // TODO Auto-generated method stub
    super.onCreate(icicle);
    setContentView(R.layout.main);
    mlocalaudio = (Button) findViewById(R.id.localaudio);
    mlocalaudio.setOnClickListener(mLocalAudioListener);
    mresourcesaudio = (Button) findViewById(R.id.resourcesaudio);
    mresourcesaudio.setOnClickListener(mResourcesAudioListener);

    mlocalvideo = (Button) findViewById(R.id.localvideo);
    mlocalvideo.setOnClickListener(mLocalVideoListener);
    mstreamvideo = (Button) findViewById(R.id.streamvideo);
    mstreamvideo.setOnClickListener(mStreamVideoListener);
  }

  private OnClickListener mLocalAudioListener = new OnClickListener() {
    public void onClick(View v) {
      Intent intent = new Intent(Test.this.getApplication(),
          MediaPlayerDemo_Audio.class);
      intent.putExtra(MEDIA, LOCAL_AUDIO);
      startActivity(intent);

    }
  };
  private OnClickListener mResourcesAudioListener = new OnClickListener() {
    public void onClick(View v) {
      Intent intent = new Intent(Test.this.getApplication(),
          MediaPlayerDemo_Audio.class);
      intent.putExtra(MEDIA, RESOURCES_AUDIO);
      startActivity(intent);

    }
  };

  private OnClickListener mLocalVideoListener = new OnClickListener() {
    public void onClick(View v) {
      Intent intent = new Intent(Test.this,
          MediaPlayerDemo_Video.class);
      intent.putExtra(MEDIA, LOCAL_VIDEO);
      startActivity(intent);

    }
  };
  private OnClickListener mStreamVideoListener = new OnClickListener() {
    public void onClick(View v) {
      Intent intent = new Intent(Test.this,
          MediaPlayerDemo_Video.class);
      intent.putExtra(MEDIA, STREAM_VIDEO);
      startActivity(intent);

    }
  };

}
//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="match_parent"
    android:layout_height="match_parent"
    >
    <Button android:id="@+id/localvideo"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" 
        android:text="local_video" 
    />
    
    <Button android:id="@+id/streamvideo"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" 
        android:text="stream_video" 
    />
    
    <Button android:id="@+id/localaudio"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" 
        android:text="local_audio" 
    />
    
    <Button android:id="@+id/resourcesaudio"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" 
        android:text="res_audio" 
    />
    
</LinearLayout>


//row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SurfaceView android:id="@+id/surface"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
    </SurfaceView>
  
</LinearLayout>

extends MediaPlayer

   
//package com.hrw.musicplayer.utils;

import java.io.IOException;

import android.media.MediaPlayer;

 class MediaPlayerUtil extends MediaPlayer {
  private static MediaPlayerUtil INSTANCE = null;

  private boolean isPause = false;

  public boolean isPause() {
    return isPause;
  }

  public void setPause(boolean isPause) {
    this.isPause = isPause;
  }

  private MediaPlayerUtil() {

  }

  public static MediaPlayerUtil getInstance(
      OnCompletionListener onCompeletionListener) {
    if (null == INSTANCE) {
      INSTANCE = new MediaPlayerUtil();
    }
    INSTANCE.setOnCompletionListener(onCompeletionListener);
    return INSTANCE;
  }

  @Override
  public void reset() {
    isPause = false;
    super.reset();
  }

  public void play() throws IllegalStateException, IOException {
    if (!isPause) {
      super.prepare();
    }
    super.start();
  }

  @Override
  public void stop() throws IllegalStateException {
    isPause = false;
    super.stop();
  }

  @Override
  public void pause() throws IllegalStateException {
    isPause = true;
    super.pause();
  }

  public void previousOrNext() throws IllegalStateException, IOException {
    isPause = false;
    play();

  }
}

MediaPlayer create and start

   
//package com.geekadoo.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;

public class MutableMediaPlayer {
  private static final String PREFS_NAME = "YANIV_PREFS";
  private static final String SILENT_MODE_PROPERTY = "silentMode";

  public static void play(Context context, int resId) {
    SharedPreferences settings = context
        .getSharedPreferences(PREFS_NAME, 0);
    boolean silent = settings.getBoolean(SILENT_MODE_PROPERTY, false);

    if (!silent) {
      MediaPlayer.create(context,  resId).start();
    }
  }

}

Multi PlayMixer

    
//package com.akjava.lib.android.sound;

import java.util.ArrayList;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

public class MultiPlayMixer {
ArrayList<Player> players=new ArrayList<Player>();
  public class Player{
    public Player(Context context,int resourceId){
      mediaPlayer=MediaPlayer.create(context, resourceId);
      /*
      mediaPlayer.setOnCompletionListener(new OnCompletionListener(){
        public void onCompletion(MediaPlayer mp) {
          //???parepare??????????
          playing=false;
        }});*/
      
    }
    public boolean reservPlay;
    public boolean playing;  //TODO media ?playing????????????
    public MediaPlayer mediaPlayer;
  }
  
  public void update(){
    for (int i = 0; i <players.size(); i++) {
      if(players.get(i).reservPlay && !players.get(i).mediaPlayer.isPlaying()){
        //players.get(i).playing=true;
        players.get(i).reservPlay=false;
        players.get(i).mediaPlayer.start();
        Log.i("myapp", "play");
        
      }
    }
  }
  public int countPlayer(){
    return players.size();
  }
  public void reservePlay(int index){
    players.get(index).reservPlay=true;
  }
  
  public void finishPlay(int index){
    players.get(index).playing=false;
  }
  public Player getPlayer(int index){
    return players.get(index);
  }
  
  public void addSound(Context context,int resourceId){
    Player player=new Player(context,resourceId);
    
    players.add(player);
  }
}

Play movie.m4v file

    
package app.test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;

public class Test extends Activity implements View.OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setOnClickListener(this);
        setContentView(button);
    }
    
    @Override
    public void onClick(View v) {
        
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file:///android_asset/movie.m4v"), "video/h264");
        startActivity(Intent.createChooser(intent, "Play Video"));
    }
}

Using Service to play media file

    
package app.test;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

class BackgroundAudioService extends Service implements OnCompletionListener {
  MediaPlayer mediaPlayer;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    mediaPlayer = MediaPlayer.create(this, R.raw.s);// raw/s.mp3
    mediaPlayer.setOnCompletionListener(this);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
    }
    return START_STICKY;
  }

  public void onDestroy() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    mediaPlayer.release();
  }

  public void onCompletion(MediaPlayer _mediaPlayer) {
    stopSelf();
  }

}

public class Test extends Activity implements OnClickListener {

  Button startPlaybackButton, stopPlaybackButton;
  Intent playbackServiceIntent;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
    stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);

    startPlaybackButton.setOnClickListener(this);
    stopPlaybackButton.setOnClickListener(this);

    playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
  }

  public void onClick(View v) {
    if (v == startPlaybackButton) {
      startService(playbackServiceIntent);
      finish();
    } else if (v == stopPlaybackButton) {
      stopService(playbackServiceIntent);
      finish();
    }
  }
}
//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"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Background Audio Player"
        />
   <Button android:text="Start Playback" android:id="@+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
   <Button android:text="Stop Playback" android:id="@+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>