rn 拍摄/预览视频react-native-image-picker和react-native-video

1、配置react-native-image-picker
	
        const options = {
        title: '上传视频',
        cancelButtonTitle:'取消',
        takePhotoButtonTitle:'拍摄',
        videoQuality:'low',   设置视频质量
        mediaType:'video',	  设置媒体格式
        chooseFromLibraryButtonTitle:'从本地相册导入',
        storageOptions: {
          skipBackup: true,
          path: 'images',
        },
      };

      ImagePicker.showImagePicker(options, (response) => {
        console.log('Response = ', response);
      
        if (response.didCancel) {
          console.log('User cancelled image picker');
        } else if (response.error) {
          console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
          console.log('User tapped custom button: ', response.customButton);
        } else {
          const source = { uri: response.uri };
			
		 视频地址回调
          this.setState({
            videoPreview:source
          });
        }
      });

 2、显示视频
    <Video 
     ref={(video)=>{this.video=video}}
     source={this.state.videoPreview} //视频回调设置的地址,url或本地文件,{require('xx.mp4')}
     volume={5} //放大声音倍数
     paused={this.state.paused}  //是否暂停
     rate={this.state.rate}  //播放速度,0暂停,1正常
     muted={false}  //静音
     resizeMode='contain' //视频适应方式
     repeat={false} //是否重复播放
     // controls={true}  //显示视频控键
     onLoadStart={this.onLoadStart}
     onLoad={this.onLoad}
     onProgress={this.onProgress}  //视频播放每隔250毫秒触发,并携带当前已播放时间
     onEnd={this.onEnd}
     onError={this.onError}
     style={styles.video}
     
     
 />

代码示例:

import React,{Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  TouchableWithoutFeedback,
  Dimensions
} from 'react-native'
import ImagePicker from 'react-native-image-picker';
import Video from 'react-native-video';

class Vedio extends Component{

    state={
        videoPreview:false,
        rate:1,
        videoReady:false,
        videoTotal:0,
        currentTime:0,
        videoProgress:0,
        paused:true,
        comments:[],
        value:'',
    }
    //加载过程获取视频总时长,onProgree内此时无法获取
    onLoad=(res)=>{
        this.setState({
            videoReady:true,
            videoTotal:res.duration
        })
    
    }

    //视频开始隐藏重新播放按钮
    onLoadStart=()=>{
        

    }
    
    //自定义进度条
    onProgress=(data)=>{
        let duration=this.state.videoTotal;
        let currentTime=data.currentTime;
        let percent=0;

        //初始加载时duration=0
        console.log(duration)
        console.log(currentTime)
        if(duration!=0)
        {
            percent=Number((currentTime/duration).toFixed(2));
        }else{
            percent=0
        }
        
        console.log( percent);
        this.setState({
            videoTotal:duration,
            currentTime:currentTime,
            videoProgress:percent,
            paused:false
        })
    }
    //视频结束显示重新播放按钮
    onEnd=()=>{
        this.setState({
            videoProgress:1,
            paused:true   //结束时必须设置暂停,使用seek方法才有效
        })
    }
    onError=(err)=>{
        console.log(err);

    }

    //点击按钮重新播放
    _replay=()=>{
        if(this.state.videoProgress==1)
        {
            this.video.seek(0);
        }
        
        this.setState({
            paused:false
        })

    }

    //配置视频
    video=()=>{
        const options = {
            title: '上传视频',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍摄',
            videoQuality:'low',
            mediaType:'video',
            chooseFromLibraryButtonTitle:'从本地相册导入',
            storageOptions: {
              skipBackup: true,
              path: 'images',
            },
          };

          ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);
          
            if (response.didCancel) {
              console.log('User cancelled image picker');
            } else if (response.error) {
              console.log('ImagePicker Error: ', response.error);
            } else if (response.customButton) {
              console.log('User tapped custom button: ', response.customButton);
            } else {
              const source = { uri: response.uri };
    
              this.setState({
                videoPreview:source
              });
            }
          });

    }

    render()
    {
        return(

            <View style={{alignItems:'center'}}>
                <View style={styles.header}>
                    <Text style={styles.tit}>录制视频</Text>
                </View>
                {
                    this.state.videoPreview?
                    <View style={{width:'100%'}}>
                        <TouchableWithoutFeedback
                            //点击视频暂停/播放 
                            onPress={()=>{
                                this.setState({
                                    paused:!this.state.paused,
                                })
                            }}
                        >
                            <Video 
                                ref={(video)=>{this.video=video}}
                                source={this.state.videoPreview} //url或本地文件,{require('xx.mp4')}
                                volume={5} //放大声音倍数
                                paused={this.state.paused}  //是否暂停
                                rate={this.state.rate}  //播放速度,0暂停,1正常
                                muted={false}  //静音
                                resizeMode='contain' //视频适应方式
                                repeat={false} //是否重复播放
                                // controls={true}  //显示视频控键
                                onLoadStart={this.onLoadStart}
                                onLoad={this.onLoad}
                                onProgress={this.onProgress}  //视频播放每隔250毫秒触发,并携带当前已播放时间
                                onEnd={this.onEnd}
                                onError={this.onError}
                                style={styles.video}
                                
                                
                            />
                        </TouchableWithoutFeedback>
                        {/* 进度条 */}
                        <View style={styles.progressBox}>
                            <View style={[styles.progress,{width:Dimensions.get('window').width*this.state.videoProgress}]}></View>
                        </View>
                        {/* 若不设置重复播放,视频结束显示重新播放按钮 */}
                        {
                            this.state.paused? 
                                        <TouchableOpacity style={styles.wrap2}
                                            onPress={this._replay}
                                        >
                                            <View style={styles.play}>
                                                    <Text style={{color:'#ccc',fontSize:30,lineHeight:50,marginLeft:5,marginBottom:5}} ></Text>
                                            </View>
                                        </TouchableOpacity>
                                        :<View></View>
                        }
                        
                        {/* 加载圆圈 */}
                        {
                            this.state.videoReady? <View></View>: <View
                                            style={styles.load}
                                        >
                                        <ActivityIndicator 
                                            size={70}
                                            color='#ccc'
                                            animating={!this.state.videoReady}
                                        />
                                    </View>
                        }
                    </View>
                    
                    :
                    <TouchableOpacity style={{width:'80%',marginTop:100}}
                        onPress={this.video}

                    >
                        <View style={styles.wrap}>
                            <Text style={styles.txt1}>点我上传视频</Text>
                            <Text style={styles.txt2}>建议时常不超过20</Text>
                        </View>
                    </TouchableOpacity>
                }
            </View>
        )
    }
}

const styles = StyleSheet.create({
    header:{
        height:40,
        backgroundColor:'#FF8858',
        position:'relative',
        width:'100%'
    },
    tit:{
        color:'white',
        fontWeight:'bold',
        fontSize:20,
        textAlign:'center',
        lineHeight:40
    },
    wrap:{
        width:'100%',
        borderColor:'orange',
        borderWidth:1,
        borderRadius:5,
        justifyContent:'center',
        alignItems:'center',
    },
    txt2:{
        fontSize:14,
        color:'#ccc',
        marginTop:10
    },
    video:{
        width:'100%',
        height:300,
        backgroundColor:'black',
        justifyContent:'center',
        alignItems:'center',
        position:'relative'
    },
    load:{
        position:'absolute',
        left:'50%',
        top:'50%',
        marginLeft:-40,
        marginTop:-30
    },
    progressBox:{
        width:'100%',
        height:3,
        backgroundColor:'#ccc'
    },
    progress:{
        width:1,
        height:2,
        backgroundColor:'green'
    },
    wrap2:{
        position:'absolute',
        bottom:'40%',
        right:'45%',
    },
    play:{
        height:50,
        width:50,
        resizeMode:'contain',
        borderWidth:1,
        borderColor:'#ccc',
        borderRadius:50,
        justifyContent:'center',
        alignItems:'center'
    }

})

export default Vedio

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/108432643
今日推荐