Android编程视频播放API之MediaPlayer用法示例

本文实例讲述了Android编程视频播放API之MediaPlayer用法。分享给大家供大家参考,具体如下:

现在项目要做音视频这块功能,这正是我相对比较薄弱的地方,项目中要用到,赶紧抓紧时间学习。前面有一编介绍不错的文章/article/121881.htm,值得学习。

这里给出一个较为简单的示例:

/**
 * Android API MediaPlayer示例
 *
 * @description:
 * @author ldm
 * @date 2016-4-20 上午10:42:06
 */
public class MediaPlayerActivity extends Activity implements OnClickListener {
  private Button mlocalvideo;
  private Button mstreamvideo;
  private Button mlocalaudio;
  private Button mresourcesaudio;
  private static final String MEDIA = "media";
  private static final int LOCAL_AUDIO = 1;
  private static final int RESOURCES_AUDIO = 3;
  private static final int STREAM_VIDEO = 5;
  @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_mediaplayer);
    initViewsAndEvents();
  }
  private void initViewsAndEvents() {
    mlocalaudio = (Button) findViewById(R.id.localaudio);
    mresourcesaudio = (Button) findViewById(R.id.resourcesaudio);
    mlocalvideo = (Button) findViewById(R.id.localvideo);
    mstreamvideo = (Button) findViewById(R.id.streamvideo);
    mlocalaudio.setOnClickListener(this);
    mresourcesaudio.setOnClickListener(this);
    mlocalvideo.setOnClickListener(this);
    mstreamvideo.setOnClickListener(this);
  }
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.localaudio:
    case R.id.localvideo:
      Intent intent = new Intent(MediaPlayerActivity.this.getApplication(),
          MediaPlayerDemo_Audio.class);
      intent.putExtra(MEDIA, LOCAL_AUDIO);
      startActivity(intent);
      break;
    case R.id.resourcesaudio:
      Intent resIn = new Intent(MediaPlayerActivity.this.getApplication(),
          MediaPlayerDemo_Audio.class);
      resIn.putExtra(MEDIA, RESOURCES_AUDIO);
      startActivity(resIn);
      break;
    case R.id.streamvideo:
      Intent streamIn = new Intent(MediaPlayerActivity.this,
          MediaPlayerDemo_Video.class);
      streamIn.putExtra(MEDIA, STREAM_VIDEO);
      startActivity(streamIn);
      break;
    }
  }
}

/**
 * OnBufferingUpdateListener可以获取视频音频流的缓冲状态;
 * OnCompletionListener播放完毕监听器
 * OnPreparedListener准备播放相关接口
 * OnVideoSizeChangedListener注册视频大小改变监听器
 * SurfaceHolder.Callback:SurfaceView监听callback
 * @description:
 * @author ldm
 * @date 2016-4-20 上午9:46:16
 */
public class MediaPlayer_Video extends Activity implements
    OnBufferingUpdateListener, OnCompletionListener,
    OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
  private static final String TAG = "MediaPlayerDemo";
  //Video宽度
  private int mVideoWidth;
  //Video高度
  private int mVideoHeight;
  //播放器MediaPlayer
  private MediaPlayer mMediaPlayer;
  //播放界面SurfaceView
  private SurfaceView mPreview;
  //媒体播放器的载体 SurfaceHolder
  private SurfaceHolder holder;
  //文件路径
  private String path;
  //Bundle数据对象
  private Bundle extras;
  private static final String MEDIA = "media";
  private static final int LOCAL_VIDEO = 1;
  private static final int RESOURCES_AUDIO = 3;
  private static final int STREAM_VIDEO = 5;
  private boolean mIsVideoSizeKnown = false;
  private boolean mIsVideoReadyToBePlayed = false;
  @SuppressWarnings("deprecation")
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.mediaplayer_2);
    mPreview = (SurfaceView) findViewById(R.id.surface);
    holder = mPreview.getHolder();
    holder.addCallback(this);
    //高版本上已经不推荐使用了 ,如果要兼容低版本(如Android 2.3或以下版本)要加上这段代码,不然播放时 只会有声音 没有图像。
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    extras = getIntent().getExtras();
  }
  private void playVideo(Integer Media) {
    doCleanUp();
    try {
      switch (Media) {
        case LOCAL_VIDEO://本地文件(如SD卡)
          /*
           * TODO:将路径变量设置为本地媒体文件路径。
           */
          path = "";//这里要填写你所播放音视频的文件路径
          if (path == "") {
            Toast
                .makeText(
                    MediaPlayer_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://流文件
          /**
           * 路径变量设置为mp4或3gpp格式的URL。应该使用Http协议。
           * 媒体播放器只能通过流的形式获取数据,所以需要:
           * 1。必须是媒体流数据。
           * 2。必须合理剪辑。
           */
          path = "";
          if (path == "") {
            // Tell the user to provide a media file URL.
            Toast
                .makeText(
                    MediaPlayer_Video.this,
                    "Please edit MediaPlayerDemo_Video Activity,"
                        + " and set the path variable to your media file URL.",
                    Toast.LENGTH_LONG).show();
          }
          break;
        case RESOURCES_AUDIO:
          //播放放在诸如res/raw文件夹下的资源文件
          //直接通过mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
          //可以参考API Demos中AudioFxDemo类文件
          break;
      }
      // 创建MediaPlayer对象,传入文件数据并设备监听
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.setDisplay(holder);
      //使用 create() 方法创建的 MediaPlayer, 直接指定了 媒体资源, 不需要再进行 调用 prepare() 方法;
      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();
  }
}

布局文件activity_mediaplayer

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

布局文件activity_mediaplayer_video

<?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>

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android数据库操作技巧总结》、《Android文件操作技巧汇总》、《Android资源操作技巧汇总》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。