web / components /VodPlayer.vue
hanbinsite's picture
feat: implement all web pages with player, search, favorites, auth, useApi composable
dfa6264
Raw History Blame Contribute Delete
3.19 kB
<template>
<div ref="containerRef" class="w-full aspect-video bg-black rounded-lg overflow-hidden relative">
<div v-if="mode === 'iframe'" class="w-full h-full">
<iframe
:src="iframeSrc"
class="w-full h-full border-0"
allowfullscreen
allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
/>
</div>
<div v-else ref="artRef" class="w-full h-full" />
</div>
</template>
<script setup lang="ts">
import Artplayer from "artplayer"
import Hls from "hls.js"
type PlayType = "m3u8" | "iframe"
const props = defineProps<{
url: string
type?: PlayType
poster?: string
parseUrl?: string | null
}>()
const emit = defineEmits<{
(e: "time-update", payload: { currentTime: number; duration: number }): void
}>()
const containerRef = ref<HTMLElement>()
const artRef = ref<HTMLElement>()
const artInstance = shallowRef<Artplayer | null>(null)
const mode = computed<PlayType>(() => {
if (props.type === "iframe") return "iframe"
const url = props.url.toLowerCase()
if (url.includes(".m3u8") || url.includes("m3u8")) return "m3u8"
if (url.startsWith("http") && !url.includes(".mp4") && !url.includes(".mkv") && props.parseUrl) return "iframe"
return "m3u8"
})
const iframeSrc = computed(() => {
if (mode.value !== "iframe") return ""
if (props.parseUrl) return `${props.parseUrl}${props.url}`
return props.url
})
function initArtplayer() {
if (!artRef.value) return
if (artInstance.value) {
artInstance.value.destroy()
artInstance.value = null
}
const url = props.url
const isM3u8 = url.toLowerCase().includes(".m3u8") || url.toLowerCase().includes("m3u8")
artInstance.value = new Artplayer({
container: artRef.value,
url,
poster: props.poster || "",
autoplay: false,
volume: 0.8,
autoSize: false,
fullscreen: true,
fullscreenWeb: true,
miniProgressBar: true,
playsInline: true,
autoPlayback: true,
setting: true,
hotkey: true,
pip: true,
lock: true,
fastForward: true,
playbackRate: true,
customType: isM3u8
? {
m3u8: (video: HTMLVideoElement, src: string) => {
if (Hls.isSupported()) {
const hls = new Hls()
hls.loadSource(src)
hls.attachMedia(video)
} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = src
}
},
}
: undefined,
})
artInstance.value.on("video:timeupdate", () => {
if (!artInstance.value) return
emit("time-update", {
currentTime: artInstance.value.currentTime,
duration: artInstance.value.duration,
})
})
}
watch(
() => [props.url, props.type, props.parseUrl],
() => {
if (mode.value === "iframe") {
if (artInstance.value) {
artInstance.value.destroy()
artInstance.value = null
}
} else {
nextTick(() => initArtplayer())
}
}
)
onMounted(() => {
if (mode.value !== "iframe") {
nextTick(() => initArtplayer())
}
})
onBeforeUnmount(() => {
if (artInstance.value) {
artInstance.value.destroy()
artInstance.value = null
}
})
</script>