Android多媒體開發筆記[1]– 利用SurfaceView + MediaPlayer開發最簡單的視頻播放器

利用android SDK 提供的接口 開發最簡單的視頻播放demo。
接下來貼出main.xml的源碼:
[html]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
 
    <SurfaceView 
        android:id="@+id/surfaceView1" 
        android:layout_width="wrap_content" 
        android:layout_height="360dp" 
        android:layout_alignParentLeft="true" 
        android:layout_alignParentRight="true" 
        android:layout_alignParentTop="true" /> 
 
</RelativeLayout> 

接下來貼出程序源碼:
[java]
package com.example.surfacemediaplayer; 
 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.os.Environment; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.view.SurfaceHolder.Callback; 
 
public class SurfaceMediaPlayer extends Activity { 
     
    SurfaceView surfaceView; 
    MediaPlayer mediaPlayer; 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_surface_media_player); 
         
        mediaPlayer=new MediaPlayer(); 
        surfaceView=(SurfaceView) this.findViewById(R.id.surfaceView1); 
         
        surfaceView.getHolder().addCallback(new Callback() {                 
            @Override 
            public void surfaceDestroyed(SurfaceHolder holder) { 
      
            } 
            @Override 
            public void surfaceCreated(SurfaceHolder holder) { 
                //開始播放 
                play(); 
            }                         
            @Override 
            public void surfaceChanged(SurfaceHolder holder, int format, int width, 
                            int height) { 
 
            } 
    });    

 
    private void play() { 
    try { 
            String path = Environment.getExternalStorageDirectory().getPath()+"/Movies/run_to_you.3gp"; 
            mediaPlayer.setDataSource(path); 
            //把視頻畫面輸出到SurfaceView 
            mediaPlayer.setDisplay(surfaceView.getHolder()); 
            mediaPlayer.prepare(); 
            //開始播放 
            mediaPlayer.start();                 
    } catch (Exception e) { 
            // TODO: handle exception 
    } 
}    
 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        getMenuInflater().inflate(R.menu.activity_surface_media_player, menu); 
        return true; 
    } 

程序運行截圖:

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *