码迷,mamicode.com
首页 > 移动开发 > 详细

android视频播放的代码

时间:2016-07-19 13:48:13      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

技术分享本地视频播放,包括播放、暂停,继续等,还有显示播放的进度。效果如下:

技术分享

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context="com.zhang.videoplay.MainActivity">

    <LinearLayout
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="10dp"
        android:orientation="horizontal">
      <Button
        android:id="@+id/playstart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="播放"/>

        <Button
            android:id="@+id/pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="暂停"/>
        <Button
            android:id="@+id/rebroadcast"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="重播"/>
        <Button
            android:id="@+id/playstop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="停止"/>
    </LinearLayout>

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_margin="20dp"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/startime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:gravity="center"
            android:text="00:00"
            />
      <SeekBar
        android:id="@+id/seekBar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_weight="6"
        />
        <TextView
        android:id="@+id/sumTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:gravity="center"
        android:text="hello"
        />
    </LinearLayout>

</LinearLayout>


2.MainActivity.java

package com.zhang.videoplay;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button plastart, pause, playstop, rebroadcast;
    private SurfaceView surfaceView;
    private SeekBar seekBar;
    private MediaPlayer mediaPlayer;
    private int currentPosition = 0;
    private boolean isPlaying;

    private TextView startTime,sumTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // 为SurfaceHolder添加回调
        surfaceView.getHolder().addCallback(callback);
        // 设置Surface不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到界面
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 为进度条添加进度更改事件
        seekBar.setOnSeekBarChangeListener(change);
    }

    private void initView() {
        plastart = (Button) findViewById(R.id.playstart);
        plastart.setOnClickListener(this);

        pause = (Button) findViewById(R.id.pause);
        pause.setOnClickListener(this);

        playstop = (Button) findViewById(R.id.playstop);
        playstop.setOnClickListener(this);

        rebroadcast = (Button) findViewById(R.id.rebroadcast);
        rebroadcast.setOnClickListener(this);

        sumTime= (TextView) findViewById(R.id.sumTime);
        startTime= (TextView) findViewById(R.id.startime);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.playstart://开始
                play(0);
                plastart.setEnabled(false);
                break;
            case R.id.playstop://停止
                stop();
                break;
            case R.id.rebroadcast://重播
                replay();
                break;
            case R.id.pause://暂停
                pause();
                break;
        }

    }

     // 添加一个Callback对象监听SurfaceView的变化
    private Callback callback = new Callback() {
        // SurfaceHolder被修改的时候回调
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.i("info", "SurfaceHolder 被销毁");
            // 销毁SurfaceHolder的时候记录当前的播放位置并停止播放
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.stop();
            }
        }

         //SurfaceView创建时触发
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            Log.i("info", "SurfaceHolder 被创建");
            if (currentPosition > 0) {
                // 创建SurfaceHolder的时候,如果存在上次播放的位置,则按照上次播放位置进行播放
                play(currentPosition);
                currentPosition = 0;
            }
        }

         //SurfaceView改变时触发
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            Log.i("info", "SurfaceHolder 大小被改变");
        }
    };

    private OnSeekBarChangeListener change = new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                // 设置当前播放的位置
                mediaPlayer.seekTo(progress);

            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            Log.i("info","onStopTrackingTouch--"+progress);
            shiftTime(startTime,progress);
        }
    };


    /**
     * 开始播放
     *
     * @param msec 播放初始位置
     */
    protected void play(final int msec) {
        // 获取视频文件地址
        String path = "/storage/emulated/0/Download/video.mp4";
        File file = new File(path);
        if (!file.exists()) {
            Toast.makeText(this, "视频文件路径错误", Toast.LENGTH_LONG).show();

            return;
        }
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 设置播放的视频源
            Log.i("info", "1111111" + file.getAbsolutePath());
            mediaPlayer.setDataSource(file.getAbsolutePath());
            // 设置显示视频的SurfaceHolder,指定视频画面输出到SurfaceView之上
            mediaPlayer.setDisplay(surfaceView.getHolder());
            Log.i("info", "开始装载");
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.i("info", "装载完成");
                    mediaPlayer.start();
                    // 按照初始位置播放
                    mediaPlayer.seekTo(msec);
                    // 设置进度条的最大进度为视频流的最大播放时长
                    seekBar.setMax(mediaPlayer.getDuration());
                    Log.i("info","2222222222-----"+mediaPlayer.getDuration());
                    //将刻度转换成时间mm:ss
                    shiftTime(sumTime,mediaPlayer.getDuration());
                    // 开始线程,更新进度条的刻度
                    new Thread() {

                        @Override
                        public void run() {
                            try {
                                isPlaying = true;
                                while (isPlaying) {
                                    int current = mediaPlayer
                                            .getCurrentPosition();
                                    seekBar.setProgress(current);
                                    sleep(1000);

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                   //将停止按钮设置不可点击
                    playstop.setEnabled(false);
                }
            });

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    playstop.setEnabled(true);
                }
            });

            mediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    // 发生错误重新播放
                    Log.i("info","onError---"+what);
                    play(0);
                    isPlaying = false;
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 重新开始播放
     */
    protected void replay() {
        if (mediaPlayer != null&& mediaPlayer.isPlaying()){
            mediaPlayer.seekTo(0);
            Toast.makeText(this,"重新播放",Toast.LENGTH_LONG).show();
            pause.setText("暂停");
            return;
        }
        play(0);
        isPlaying = false;


    }

    /**
     * 暂停或继续
     */
    protected void pause() {
        if (pause.getText().toString().trim().equals("继续")) {
            pause.setText("暂停");
            mediaPlayer.start();
            Toast.makeText(this, "继续播放", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            pause.setText("继续");
            Toast.makeText(this,"暂停播放",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 停止播放
     */
    protected void stop() {

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            playstop.setEnabled(true);
            isPlaying = false;
        }
    }

    //将刻度转换为时间

    private void shiftTime(TextView view,int time){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        date.setTime(time);
        String str = sdf.format(date);
        Log.i("info","33333333-----"+str);
        view.setText(str);
    }

}



3.加入权限

 <!-- 写外部存储即sdcard的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!-- 打开关闭sdcard的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>





android视频播放的代码

标签:

原文地址:http://blog.csdn.net/zhang106209/article/details/51953664

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!