expo react-native視訊播放元件

一條舞動青春的鹹魚發表於2020-12-01

前置準備

安裝 expo-av(播放器前置),expo-video-player(播放器元件),expo-screen-orientation(切換螢幕方向)

效果圖

縱向

在這裡插入圖片描述
橫向
在這裡插入圖片描述

基礎的視訊元件程式碼

<VideoPlayer
                inFullscreen={true}
                videoProps={{
                    shouldPlay: true,
                    resizeMode: Video.RESIZE_MODE_CONTAIN,
                    source: {
                    uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4',
                    },
                }}
                width= {videowidth}
                height= {videoheight}
                }}
                />

在此基礎上新增全屏功能
長寬比為 10:9

import { StyleSheet,  View,Dimensions,StatusBar} from 'react-native';
import React, { useState,useEffect} from 'react';
import * as ScreenOrientation from 'expo-screen-orientation';
import { Audio, Video } from 'expo-av';
import VideoPlayer from 'expo-video-player'
const {height, width} = Dimensions.get('window');
const VideoPage=(props)=>{

    const [screenFlag, setscreenFlag] = useState(1)
    const [videowidth, setvideowidth] = useState(Dimensions.get('window').width)
    const [videoheight, setvideoheight] = useState(Dimensions.get('window').width*9/10)
    return(
        <>
        
        {
            screenFlag==1?(
                <StatusBar backgroundColor="#87CEFA"/>
            ):(<StatusBar hidden={true}/>)
        }
        <View style={{ flex: 1,backgroundColor:'#f5f6f7',}}>
        <View>
        
            <VideoPlayer
                inFullscreen={true}
                videoProps={{
                    shouldPlay: true,
                    resizeMode: Video.RESIZE_MODE_CONTAIN,
                    source: {
                    uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4',
                    },
                }}
                width= {videowidth}
                height= {videoheight}
                
                switchToPortrait={()=>{
                    if(screenFlag==1){
                        ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE_LEFT)
                        setscreenFlag(0)
                        setvideowidth(Dimensions.get('window').height)
                        setvideoheight(Dimensions.get('window').width)
                    }else{
                        ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP)
                        setscreenFlag(1)
                        setvideowidth(width)
                        setvideoheight(width*9/10-1)
                        //console.log(videowidth+","+videoheight)
                    }
                    
                }}
                />
        </View>
        </View>
        
        </>
    )
}
export default VideoPage

相關文章