SurfaceView播放视频

SurfaceView播放视频


RelativeLayout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.examday11_4_1.surfaceview.MySurfaceView
        android:id="@+id/sv"
        android:layout_width="match_parent"
        android:layout_height="250dp" />

    <TextView
        android:id="@+id/te_nowTiem"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/sv"
        android:layout_marginLeft="60dp"
        android:layout_marginBottom="10dp"
        android:text="00:00" />

    <SeekBar
        android:id="@+id/sb"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/sv"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp" />

    <TextView
        android:id="@+id/te_allTiem"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/sv"
        android:layout_marginLeft="320dp"
        android:layout_marginBottom="10dp"
        android:text="00:00" />

    <Button
        android:id="@+id/but_play"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignBottom="@+id/sv"
        android:layout_marginLeft="10dp"
        android:text="S/P"
        android:textSize="10sp" />

</RelativeLayout>

mySurfaceView

package com.example.examday11_4_1.surfaceview;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder surfaceHolder;
    private MediaPlayer mediaPlayer;

    public MySurfaceView(Context context) {
        super(context);
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
        }
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void setDataPath(String path){
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mediaPlayer.setDisplay(surfaceHolder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    //暂停/开始播放
    public void playOrNo(){
        if (mediaPlayer!=null){
            if (mediaPlayer.isPlaying()){
                mediaPlayer.pause();
            }else {
                mediaPlayer.start();
            }
        }
    }

    //拖动更新进度
    public void seekTo(int progress){
        if (mediaPlayer!=null){
            int duration = mediaPlayer.getDuration();
            int current = progress * duration /100;
            mediaPlayer.seekTo(current);
        }
    }

    //获取播放进度
    public int getProgress(){
        if (mediaPlayer!=null){
            int druation = mediaPlayer.getDuration();
            int currentPosition = mediaPlayer.getCurrentPosition();
            int progress = currentPosition * 100 / druation;
            return progress;
        }
        return 0;
    }

    //获取播放时长
    public String getCurrentTime(){
        if (mediaPlayer!=null){
            long currentPostion = mediaPlayer.getCurrentPosition();
            SimpleDateFormat format = new SimpleDateFormat("mm:ss");
            String f = format.format(currentPostion);
            return f+"";

        }
        return "";
    }

    //获取时长
    public  String getDuration(){
        if (mediaPlayer!=null){
            long duration = mediaPlayer.getDuration();
            SimpleDateFormat format = new SimpleDateFormat("mm:ss");
            return format.format(duration)+"";
        }
        return "";
    }

}

MainActivity

package com.example.examday11_4_1;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.examday11_4_1.surfaceview.MySurfaceView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private MySurfaceView mySurfaceView;
    private TextView teNowTiem;
    private SeekBar sb;
    private TextView teAllTiem;
    private Button butPlay;
    private Timer timer;
    private Handler handler = new Handler();
    private String path ="http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE
            },100);
        }
        initView();
        initTimer();

    }

    private void initTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final String currentTime = mySurfaceView.getCurrentTime();
                final String duration = mySurfaceView.getDuration();
                final int progress = mySurfaceView.getProgress();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        sb.setProgress(progress);//设置进度条
                        teAllTiem.setText(duration);//设置总时长
                        teNowTiem.setText(currentTime);//设置当前时长
                    }
                });
            }
        },0,100);
    }

    private void initView() {
        mySurfaceView = (MySurfaceView) findViewById(R.id.sv);
        mySurfaceView.setDataPath(path);
        teNowTiem = (TextView) findViewById(R.id.te_nowTiem);
        sb = (SeekBar) findViewById(R.id.sb);
        teAllTiem = (TextView) findViewById(R.id.te_allTiem);
        butPlay = (Button) findViewById(R.id.but_play);

        //设置拖动
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    mySurfaceView.seekTo(progress);//视频播放拖动
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //暂停播放
        butPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mySurfaceView.playOrNo();
            }
        });

    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SurfaceViewAndroid 中专门用来绘制视频的 View,它可以在一个单独的线程中进行绘制,可以提高视频播放的效率和流畅度。以下是一个简单的 SurfaceView 播放视频的示例: 1. 在布局文件中定义 SurfaceView: ``` <SurfaceView android:id="@+id/surfaceView" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 2. 在 Activity 中获取 SurfaceView 对象,并设置 SurfaceHolder.Callback 监听: ``` public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback { private SurfaceView surfaceView; private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); surfaceView = findViewById(R.id.surfaceView); SurfaceHolder holder = surfaceView.getHolder(); holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder holder) { // 初始化 MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDisplay(holder); try { mediaPlayer.setDataSource("http://example.com/video.mp4"); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // do nothing } @Override public void surfaceDestroyed(SurfaceHolder holder) { // 释放 MediaPlayer mediaPlayer.release(); } } ``` 3. 在 SurfaceHolder.Callback 监听中初始化 MediaPlayer,并将 SurfaceView 的 SurfaceHolder 对象设置给 MediaPlayer,然后设置数据源并调用 prepare() 和 start() 方法开始播放视频。 注意:以上代码中的视频地址是一个示例地址,实际使用时需要替换为真实的视频地址。同时,为了避免网络请求阻塞主线程,最好在子线程中进行网络请求和视频播放。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值