vue3使用shaka-player

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3使用shaka-player

简单卟容易   2022-09-29 我要评论

正文

Shaka Player 是谷歌公司对外开源的一款 JavaScript 类库,详细请看谷歌官方API文档

开始使用

我们可以使用 npm 下载

npm i shaka-player

做成组件shakaPlayer

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import shaka from "shaka-player/dist/shaka-player.ui.js";
import "../../node_modules/shaka-player/dist/controls.css"; // 注意路径
const props = defineProps({
  src: { type: String, required: true },
  poster: { type: String, default: "" },
  autoplay: { type: Boolean, default: false }
});
onMounted(() => {
  initApp();
});
onBeforeUnmount(() => {
  player && player.destroy();
});
const initApp = () => {
  if (shaka.Player.isBrowserSupported()) {
    initPlayer();
  } else {
    console.error("Browser not supported!");
  }
};
const videoPlayer = ref();
const videoContainer = ref();
let player = null;
const initPlayer = () => {
  player = new shaka.Player(videoPlayer.value);
  const ui = new shaka.ui.Overlay(
    player,
    videoContainer.value,
    videoPlayer.value
  );
  ui.configure({
    // 自定义控件
    controlPanelElements: [
      "time_and_duration", // 进度
      "spacer",
      "mute", // 静音
      "volume", // 音量
      "fullscreen", // 全屏
      "overflow_menu"
    ],
    overflowMenuButtons: [
      "picture_in_picture", // 画中画
      "playback_rate" // 倍速
    ],
    playbackRates: [0.5, 1, 1.5, 2], // 倍速选项
    // 视频进入全屏时设备是否应旋转到横向模式
    forceLandscapeOnFullscreen: false
  });
  loadPlayer();
};
const loadPlayer = async () => {
  try {
    await player.load(props.src);
  } catch (e) {
    onError(e);
  }
};
const onError = (error) => {
  console.error("Error code", error.code, "object", error);
};
const play = () => videoPlayer.value && videoPlayer.value.play();
const pause = () => videoPlayer.value && videoPlayer.value.pause();
watch(
  () => props.src,
  () => initPlayer()
);
defineExpose({ play, pause });
</script>
<template>
  <div ref="videoContainer" class="max-w-full">
    <video
      ref="videoPlayer"
      class="full"
      :poster="poster"
      :autoplay="autoplay"
      muted
    ></video>
  </div>
</template>
<style scoped>
.max-w-full {
  max-width: 100%;
}
.full {
  width: 100%;
  height: 100%;
}
</style>

使用方式

<shaka-player
  class="video"
  :src="src"
  :poster="poster"
  autoplay
></shaka-player>
.video {
  width: 100%;
  height: 200px;
}

注意事项

默认视频控件是显示所有的,允许我们自定义。

我们可以直接使用 video 原生方法、事件和属性。

宽高可以用class样式设置。

Shaka Player不支持Vue响应对象,player 不能用 ref 来声明。

移动端视频默认静音时,autoplay 才会生效。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们