android视频播放MediaPlayer+SurfaceView

来源:互联网 发布:汽车图解软件哪个好 编辑:程序博客网 时间:2024/06/11 20:15

VideoActivity

package com.example.wy.videodemo;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.pm.ActivityInfo;import android.content.res.AssetFileDescriptor;import android.content.res.Configuration;import android.graphics.Bitmap;import android.media.AudioManager;import android.media.MediaPlayer;import android.media.MediaPlayer.OnErrorListener;import android.media.MediaPlayer.OnPreparedListener;import android.os.Bundle;import android.util.Log;import android.view.SurfaceHolder;import android.view.SurfaceHolder.Callback;import android.view.SurfaceView;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.view.WindowManager;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;/** * 视频播放 */public class VideoActivity extends Activity implements OnPreparedListener,        OnClickListener, OnSeekBarChangeListener {    private RelativeLayout rl_video;//上方视频    private SurfaceView sv_video; // 双缓冲    private MediaPlayer mp_video;    private Button bt_play_pause;    private Button bt_change;    private SeekBar sb_progress;    private SeekBar sb_vol;    private AudioManager am;    private MyReceiver receiver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_video);        initView();        initData();    }    private void initView() {        rl_video = (RelativeLayout) findViewById(R.id.rl_video);        sv_video = (SurfaceView) findViewById(R.id.sv_video);        bt_play_pause = (Button) findViewById(R.id.bt_play_pause);        bt_change = (Button) findViewById(R.id.bt_change);        sb_progress = (SeekBar) findViewById(R.id.sb_progress);        sb_vol = (SeekBar) findViewById(R.id.sb_vol);        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);    }    private void initData() {        // 兼容2.3,否则只有声音没有画面        // sv_video.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);        //增量逻辑,覆盖逻辑        sv_video.getHolder().addCallback(new Callback() {            @Override            public void surfaceCreated(SurfaceHolder holder) {                //  surface可见的时候,处于上层的时候                Log.e("pid", "surfaceCreated");                play();            }            @Override            public void surfaceDestroyed(SurfaceHolder holder) {                // surface不可见的时候                Log.e("pid", "surfaceDestroyed");                stop();            }            @Override            public void surfaceChanged(SurfaceHolder holder, int format,                    int width, int height) {                Log.e("pid", "surfaceChanged");            }        });        receiver = new MyReceiver();        registerReceiver(receiver, new IntentFilter(                "android.media.VOLUME_CHANGED_ACTION"));        sb_vol.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));        sb_vol.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));        bt_play_pause.setOnClickListener(this);        bt_change.setOnClickListener(this);        sb_progress.setOnSeekBarChangeListener(this);        sb_vol.setOnSeekBarChangeListener(this);        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);    }    /**     * 播放视频     */    private void play() {        mp_video = new MediaPlayer();        AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.por);        try {            // 设置视频资源            mp_video.setDataSource(afd.getFileDescriptor(),                    afd.getStartOffset(), afd.getLength());            mp_video.setLooping(true);            mp_video.setDisplay(sv_video.getHolder());            mp_video.prepareAsync();            mp_video.setOnPreparedListener(this);        } catch (Exception e) {            e.printStackTrace();        }    }    private void stop() {        try {            if (mp_video != null) {                mp_video.pause();                mp_video.stop();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            canProgress = false;            mp_video.release();            mp_video = null;        }    }    @Override    public void onPrepared(MediaPlayer mp) {        // 视频准备完成,可以播放了,先设置视频区域大小        mp.setOnErrorListener(new OnErrorListener() {            @Override            public boolean onError(MediaPlayer mp, int what, int extra) {                return false;            }        });        setVideoParams(                mp,                getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);        sb_progress.setMax(mp.getDuration());        mp.start();        startProgress();    }    private boolean canProgress;    /**     * 视频进度条开始     */    private void startProgress() {        canProgress = true;        new Thread() {            public void run() {                while (canProgress) {                    // runOnUiThread(new Runnable() {                    // public void run() {                    // //在主线程中执行                    // }                    // });                    try {                        sb_progress.setProgress(mp_video.getCurrentPosition());                        sleep(500);                    } catch (Exception e) {                        e.printStackTrace();                    }                }            };        }.start();    }    /**     * 根据手机屏幕,设置视频区域大小,16:9     */    private void setVideoParams(MediaPlayer mp, boolean isLand) {        ViewGroup.LayoutParams pa_rl = rl_video.getLayoutParams();        ViewGroup.LayoutParams pa_sv = sv_video.getLayoutParams();        // int s_width=getWindowManager().getDefaultDisplay().getWidth();        float s_width = getResources().getDisplayMetrics().widthPixels;        float s_height = getResources().getDisplayMetrics().widthPixels / 16f * 9f;        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);        if (isLand) {            s_height = getResources().getDisplayMetrics().heightPixels;            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);        }        pa_rl.width = (int) s_width;        pa_rl.height = (int) s_height;        float v_width = mp.getVideoWidth();        float v_height = mp.getVideoHeight();        float s_por = s_width / s_height;        float v_por = v_width / v_height;        if (v_por < s_por) { // 16:12 16:9            pa_sv.height = (int) s_height;            pa_sv.width = (int) (s_height * v_por);        } else {// 19:9 16:9            pa_sv.height = (int) (s_width / v_por);            pa_sv.width = (int) s_width;        }        rl_video.setLayoutParams(pa_rl);        sv_video.setLayoutParams(pa_sv);    }    @Override    public void onClick(View v) {        switch (v.getId()) {        case R.id.bt_play_pause:            try {                if (bt_play_pause.getText().equals("暂停")) {                    // 暂停                    mp_video.pause();                    bt_play_pause.setText("继续");                } else {                    // 点击了继续                    mp_video.start();                    bt_play_pause.setText("暂停");                }            } catch (Exception e) {                e.printStackTrace();            }            break;        case R.id.bt_change:            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {                // 变成横屏                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);            } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {                // 变成竖屏                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);            }            break;        }    }    @Override    public void onConfigurationChanged(Configuration newConfig) {        super.onConfigurationChanged(newConfig);        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {            // 变成横屏了            setVideoParams(mp_video, true);        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {            //变成竖屏了            setVideoParams(mp_video, false);        }    }    @Override    public void onProgressChanged(SeekBar seekBar, int progress,            boolean fromUser) {        if (!fromUser)            return;        switch (seekBar.getId()) {        case R.id.sb_progress:            try {                mp_video.seekTo(progress);            } catch (Exception e) {                e.printStackTrace();            }            break;        case R.id.sb_vol:            am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);            break;        }    }    @Override    public void onStartTrackingTouch(SeekBar seekBar) {    }    @Override    public void onStopTrackingTouch(SeekBar seekBar) {    }    class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            // 监听系统音量变化            sb_vol.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));        }    }}

布局文件

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <RelativeLayout        android:id="@+id/rl_video"        android:layout_width="match_parent"        android:layout_height="200dip"        android:background="#000" >        <SurfaceView            android:id="@+id/sv_video"            android:layout_width="match_parent"            android:layout_height="200dip"            android:layout_centerInParent="true" />        <Button            android:id="@+id/bt_play_pause"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="暂停" />        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_alignParentBottom="true"            android:layout_toLeftOf="@+id/bt_change" >            <SeekBar                android:id="@+id/sb_progress"                android:layout_width="0dip"                android:layout_height="wrap_content"                android:layout_marginRight="4dip"                android:layout_weight="2" />            <SeekBar                android:id="@+id/sb_vol"                android:layout_width="0dip"                android:layout_height="wrap_content"                android:layout_weight="1" />        </LinearLayout>        <Button            android:id="@+id/bt_change"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentBottom="true"            android:layout_alignParentRight="true"            android:text="切换" />    </RelativeLayout></RelativeLayout>
0 0
原创粉丝点击