直播软件开发Android项目之视频播放器

视频播放
1)VideoView控件播放视频
VideoView控件是播放视频用的,借助它可以完成一个简易的视频播放器。
①在activity_main.xml中编写相应的控件

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/bt_play"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="150dp"
        android:src="@android:drawable/ic_media_play" />
    <VideoView
        android:id="@+id/videoview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

②在MainActivity实现SeekBar.OnSeekChangeListener接口与SurfaceHolder.Callback接口,并重写这两个接口中对应的方法,在这些方法中实现播放视频的。

package com.example.videoview;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements
        View.OnClickListener {
    private VideoView videoView;
    private MediaController controller;
    ImageView iv_play;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView = (VideoView) findViewById(R.id.videoview);
        iv_play = (ImageView) findViewById(R.id.bt_play);
        //拼出在资源文件夹下的视频文件路径String字符串
        String url = "android.resource://" + getPackageName() + "/" + R.raw.video;
        //字符串解析成Uri
        Uri uri = Uri.parse(url);
        //设置videoview的播放资源
        videoView.setVideoURI(uri);
        //VideoView绑定控制器
        controller = new MediaController(this);
        videoView.setMediaController(controller);
        iv_play.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_play:
                play();
                break;
        }
    }
    // 播放视频
    private void play() {
        if (videoView != null && videoView.isPlaying()) {
            iv_play.setImageResource(android.R.drawable.ic_media_play);
            videoView.stopPlayback();
            return;
        }
        videoView.start();
        iv_play.setImageResource(android.R.drawable.ic_media_pause);
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                iv_play.setImageResource(android.R.drawable.ic_media_play);
            }
        });
    }
}

你可能感兴趣的:(技术类,android,webview,移动开发,android,studio,ios)