Skip to content

Instantly share code, notes, and snippets.

@espeon
Last active October 28, 2022 15:41
Show Gist options
  • Select an option

  • Save espeon/8e980fcd35ef686b9f2386d8c6da8f65 to your computer and use it in GitHub Desktop.

Select an option

Save espeon/8e980fcd35ef686b9f2386d8c6da8f65 to your computer and use it in GitHub Desktop.
(react) plyr wrapper, supports quality selection. example here: https://csb-hwgis.netlify.app/
import React, { useEffect, useRef } from "react";
import Plyr from "plyr";
import "plyr/dist/plyr.css";
import Hls from "hls.js";
import "./player.css";
export default function Player({ isLive = false, playbackURL }) {
const videoRef = useRef(null);
const playerRef = useRef(null);
// const previewSrc = `https://image.mux.com/${playbackId}/storyboard.png`;
useEffect(() => {
const defaultOptions = {
captions: { active: true, update: true, language: "en" }
};
const videoSrc = playbackURL;
if (videoSrc.includes(".m3u8")) {
const hls = new Hls();
hls.loadSource(playbackURL);
hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
const availableQualities = hls.levels.map((l) => l.height);
availableQualities.unshift(0); //prepend 0 to quality array
defaultOptions.quality = {
default: "0", //Default - AUTO
options: availableQualities,
forced: true,
onChange: (e) => updateQuality(e, hls)
};
hls.on(Hls.Events.LEVEL_SWITCHED, function (event, data) {
var span = document.querySelector(
".plyr__menu__container [data-plyr='quality'][value='0'] span"
);
if (hls.autoLevelEnabled) {
span.innerHTML = `Auto (${hls.levels[data.level].height}p)`;
} else {
span.innerHTML = `Auto`;
}
});
console.log("player");
playerRef.current = new Plyr(videoRef.current, defaultOptions);
});
hls.attachMedia(videoRef.current);
} else {
playerRef.current = new Plyr(videoRef.current, defaultOptions);
playerRef.current.source = {
type: "video",
title: "Example title",
sources: [
{
src: playbackURL,
type: "video/mp4"
}
]
};
}
function updateQuality(newQuality, hls) {
console.log("quality is", newQuality);
if (newQuality === "0") {
hls.currentLevel = -1; //Enable AUTO quality if option.value = 0
console.log("Auto quality selection");
} else {
hls.levels.forEach((level, levelIndex) => {
if (level.height === newQuality) {
console.log("Found quality match with " + newQuality);
hls.currentLevel = levelIndex;
}
});
}
}
}, [videoRef, playbackURL, isLive]);
return (
<div className="container">
<video muted controls ref={videoRef} />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment