直播软件开发Android项目之视频播放器
16lz
2021-01-26
视频播放
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的View的VISIBLE,INVISIBLE,GONE三个 属性
- Android(安卓)可拖拽悬浮按钮
- Android(安卓)WebRTC 音视频开发总结(二)
- Android(安卓)listview子控件的的点击事件
- android 常用控件
- Android动态改变控件的位置
- NDK的sample里hello-gl2编译通过,运行报错
- Airtest Project Android(安卓)UI自动化测试笔记
- 《Monkey Android》第6课点击事件的四种写法