思考
在目前的阿里云播放器中,没有提供相关的npm包,所以对开发来说十分不友好。在今天的开发过程中接触到了NextJS,因为项目需要所以进行了NextJS的阿里云播放器接入,以下是过程记录。
因为NextJS不能获取到window和document,故取消用createElement异步创建引入脚本和样式。
运行步骤
组件引入
{this.state.showPlayer&& console.log('player ', instance)}>}
使用state对播放器进行显示是因为播放器在文件没有配置完整的情况下先独自完成渲染,导致无法获取到配置文件,所以需要再配置完成时再将播放器进行展示
相关文件
components/aliplayer/index.js //播放器核心文件
pages/player.js //组件调用页面
实现方式
一、创建相关代码
index.js //组件代码
import React, {Component} from 'react'
class Aliplayer extends Component {
state = {
id: null,
config: null,
onGetInstance: null,
}
componentWillMount() {
const id = `aliplayer-${Math.floor(Math.random() * 1000000)}`;
this.setState({id})
}
componentDidMount() {
let {config, onGetInstance} = this.props
if (!config) {
throw new Error('Missing Aliplayer config');
}
const player = this.player
const {id} = this.state
if (!id || player.current) {
return
}
const Aliplayer = window.Aliplayer;
if (player.current) {
return
}
player.current = new Aliplayer({
...config,
"id": id,
}, (player) => {
onGetInstance && onGetInstance(player);
});
}
render() {
const {id} = this.state
return ( this.player = ref} id={id}>)
}
}
export default Aliplayer
player.js
此次将资源文件通过引用该组件的Head插入,因为在组件引入资源文件时会产生请求不到 new Aliplayer()
。如果调用的页面比较多,可以放在母版页进行引入,
import React,{Component} from 'react'
import Aliplayer from "../components/aliplay";
import Head from 'next/head'
export default class Player extends Component {
state = {
showPlayer: false,
loadVideoFailure: false,
loadCourseInfoFailure: false,
errMessage: '视频加载失败',
instance: null,
height: '100%',
playerConfig: {
vid: "",
playauth: "",
width: '100%',
height: '100%',
autoplay: false, // 自动播放
// showBarTime: '1000',
useH5Prism: true, // 播放器类型:html5
preload: true,
}
]
}
}
constructor() {
super(...arguments)
this.videoPlayer = React.createRef();
this.init()
}
init() {
this.getCourseDetail()
}
getCourseDetail() {
const data={vid:'',playAuth:""} //请求到的数据
this.state.playerConfig.vid = data.vid
this.state.playerConfig.playauth = data.playAuth
this.setState({playerConfig: this.state.playerConfig, showPlayer: true, loadVideoFailure: false})
}
handleRefreshBtnClick(){
window.location.reload()
}
render() {
const {errMessage} = this.state
return (