/**
*作者:gxx
*时间:2024/11/1 14:32
*功能:
**/
import { media } from "@kit.MediaKit";
import { BusinessError } from "@kit.BasicServicesKit";
import { promptAction } from "@kit.ArkUI";
export class MediaPlayer {
private player: media.AVPlayer
private source: media.AVFileDescriptor | string
private state: media.AVPlayerState = 'idle'
constructor(player: media.AVPlayer, source: media.AVFileDescriptor | string) {
// 创建出来player
this.player = player;
// 设置监听
this.setListener()
this.source = source;
// 设置播放资源
if (typeof source == 'string') {
this.player.url = source
} else {
this.player.fdSrc = source
}
}
// 设置监听
private setListener() {
// 播放错误
this.player.on('error', (err: BusinessError) => {
console.error('gxxt play err: ', err.message)
})
// 播放完毕
this.player.on("endOfStream", () => {
console.log('gxxt play 完毕')
})
this.player.on("stateChange", (state, reason) => {
// 更新当前状态
this.state = state
switch (state) {
case 'idle':
console.log('gxxt play 刚创建')
break;
case 'initialized':
console.log('gxxt play 初始化好了播放资源')
this.player.prepare()
break;
case 'prepared':
console.log('gxxt play 准备好的状态')
break;
case 'playing':
console.log('gxxt play 播放中状态')
break;
case 'paused':
console.log('gxxt play 暂停的状态')
break;
case 'stopped':
console.log('gxxt play 停止的状态')
break;
case 'released':
console.log('gxxt play 释放资源')
break;
}
})
}
play() {
// 如果当前状态是准备态或者暂停可以直接播放 否则先准备
if (this.state == 'prepared' || this.state == 'paused') {
this.player.play()
} else if (this.state == 'stopped') {
this.player.prepare(() => {
// 停止状态进来的 要先准备 再开始播放
this.player.play()
})
}
}
pause() {
// 只有是播放状态才能暂停
if (this.state == 'playing') {
this.player.pause()
} else {
promptAction.showToast({ message: '当前状态不支持暂停' })
}
}
// 停止播放
stop() {
this.player.stop()
}
//释放资源
release() {
this.player.release()
}
seekto(time: number) {
// 滑动播放时间
if (time < this.player.duration) {
this.player.seek(time)
}
}
}
评论