youtube-player 是 YouTube IFrame Player API (YIPA) 的封装。可以在自己网站上播放YouTube视频。
开始使用
使用 npm
下载
npm i youtube-player
封装成组件youtubePlayer
新建一个youtubePlayer.vue文件
<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import YouTubePlayer from "youtube-player";
const props = defineProps({
id: { type: String, default: "" },
src: { type: String, required: true },
width: { type: Number, default: 0 },
height: { type: Number, default: 0 },
playerVars: {
type: Object,
default() {
return {};
}
}
});
const emit = defineEmits(["ended", "play", "pause"]);
onMounted(() => {
initPlayer();
loadPlayer();
addStateChange();
});
onBeforeUnmount(() => {
removeStateChange();
player && player.destroy();
player = null;
});
const getVideoId = () => {
try {
return new URL(props.src).searchParams.get("v") || "";
} catch (error) {
return "";
}
};
let player = null;
const initPlayer = () => {
try {
player = YouTubePlayer(`youtube-${props.id}`, {
videoId: getVideoId(),
width: props.width,
height: props.height,
// playerVars 播放器其它参数配置
playerVars: {
playsinline: 1,
...props.playerVars
}
});
} catch (error) {
console.log(error);
}
};
const loadPlayer = () => {
try {
player.loadVideoById(getVideoId());
} catch (error) {
console.log(error);
}
};
const play = () => player && player.playVideo();
const pause = () => player && player.pauseVideo();
// -1(未开始)0(已结束)1(正在播放)2(已暂停)3(正在缓冲)5(视频已插入)
let stateChangeListener;
const addStateChange = () => {
stateChangeListener = player && player.on("stateChange", (event) => {
if (event.data === 0) emit("ended");
if (event.data === 1) emit("play");
if (event.data === 2) emit("pause");
});
};
const removeStateChange = () => {
if (stateChangeListener && player) player.off(stateChangeListener);
};
watch(
() => props.src,
() => loadPlayer()
);
watch(
() => [props.width, props.height],
() => {
player?.setSize && player.setSize(props.width, props.height);
}
);
defineExpose({ play, pause });
</script>
<template>
<div class="youtube-video">
<div :id="'youtube-' + id"></div>
</div>
</template>
<style lang="scss" scoped>
.youtube-video {
width: 100%;
overflow: hidden;
}
</style>
如何使用
<youtube-player src="https://www.youtube.com/watch?v=uRzs2kS3Blg"></youtube-player>
播放器参数设置 - 例如如何不显示全屏按钮?
<youtube-player :playerVars="{ fs: 0 }" src="https://www.youtube.com/watch?v=uRzs2kS3Blg"></youtube-player>
注意事项
播放器有默认宽高,只能是px,需要做响应式的要自己动态获取宽高在重新设置。
有些播放器参数可能不生效,这也是没办法,一切由YouTube解释为准。
常用参数
参数 | |
---|---|
autoplay | 是否在播放器加载时自动开始播放初始视频。支持的值为 0 或 1。默认值为 0。 |
controls | 视频播放器控件是否会显示。支持的值为 0 或 1。默认值为 1。 |
fs | 视频播放器全屏按钮是否会显示。支持的值为 0 或 1。默认值为 1。 |
playsinline | 此参数用于控制视频在 iOS 设备上的 HTML5 播放器中播放时,是以内嵌方式还是全屏模式播放。支持的值为 0 或 1。默认值为 0 全屏。 |
hl | 设置播放器的界面语言。如繁体字:zh-HK,默认英文。 |
常用API
playVideo()
播放当前已插入/已加载的视频。
pauseVideo()
暂停当前正在播放的视频。
stopVideo()
停止和取消加载当前视频。
mute()
使播放器静音。
unMute()
取消播放器静音。
setSize(width:Number, height:Number)
设置包含播放器的<iframe>
的大小。
destroy()
移除包含播放器的 <iframe>
。