vue+node Implementation of Video Play Online Example Code
- 2021-08-31 07:04:03
- OfStack
1. node server
Data stream transmission, online cache
// Get parameters
var params=urldeal.parse(req.url,true).query
const ROOT_PATH = process.cwd();// You must use an absolute path, and using a relative path will download files directly
let path =ROOT_PATH+params.url;
let stat = fs.statSync(path); // Get file information
let fileSize = stat.size;
let range = req.headers.range;
if (range) {
// Have range The head is used only 206 Status code
let parts = range.replace(/bytes=/, "").split("-");
let start = parseInt(parts[0], 10);
let end = parts[1] ? parseInt(parts[1], 10) : start + 9999999;
// end At the end, the value is fileSize - 1
end = end > fileSize - 1 ? fileSize - 1 : end;
let chunksize = (end - start) + 1;
let file = fs.createReadStream(path, { start, end });
let head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
};
res.writeHead(206, head);
file.pipe(res); //Node In Server End HTTP response Yes Writable Stream
} else {
let head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
};
res.writeHead(200, head);
fs.createReadStream(path).pipe(res);
}
2. vue client
1. Install the video-player plug-in
cnpm install vue-video-player --save
2. References in components
<video-player class="video-player vjs-custom-skin"
ref="videoPlayer"
:playsinline="true"
:options="playerOptions"
></video-player>
3. Data in the invoked data
data() {
return {
// Video playback
playerOptions: {
playbackRates: [0.5, 1.0, 1.5, 2.0], // Play speed
autoplay: false, // If true, Start playback when the browser is ready.
muted: false, // By default, any audio will be eliminated.
loop: false, // Cause video 1 Start over when it's over.
preload: 'auto', // It is recommended that browsers use the <video> Whether you should start downloading video data after loading the element. auto Browser selects best behavior , Start loading video now (if your browser supports it)
language: 'zh-CN',
aspectRatio: '16:9', // Put the player in fluent mode and use this value when calculating the dynamic size of the player. The value should represent the 1 Percentage ratio - Two numbers separated by colons (for example "16:9" Or "4:3" )
fluid: true, // When true When, Video.js player Will have fluid size. In other words, it will be scaled to fit its container.
sources: [{
type: "",
//src: require('@/assets/'+this.vurl)//url Address
src: 'http://localhost:10086/videos?url=/public/videos/'+this.vurl, //url Address, the request needs to include the specific video file name
}],
poster: '', // Your cover address
// width: document.documentElement.clientWidth,
notSupportedMessage: ' This video is temporarily unplayable. Please try again later ', // Allow overrides Video.js The default information displayed when the media source cannot be played.
controlBar: {
timeDivider: true,
durationDisplay: true,
remainingTimeDisplay: false,
fullscreenToggle: true // Full screen button
}
}
}
},
Appendix: vue+flvjs to play live stream FLV, how to disconnect the previous live stream during paging
Use flvjs library to play flv files at the same time, need paging found, before the live stream did not disconnect, very affect the performance, online reference to the following code to achieve disconnect the live stream on the page
// Destroy Player Instances
closePlayer() {
if (this.player.length > 0) {
this.player.forEach((item) => {
item.destroy(true);
item.off('ended', function () {});
item.off('error', function () {});
item = null;
});
this.player = [];
}
},
// Initialize the player
initPlayer(id, url, img) {
let doms = document.getElementById(id);
doms.innerHTML = '';
this.player.push(
new FlvPlayer({
id: id,
url: url,
poster: img,
isLive: true,
autoplay: true,
volume: id == 'videos0' ? 0.5 : 0,
preloadTime: 10,
minCachedTime: 5,
cors: true,
})
);
this.player[this.player.length - 1].on('ended', () => {
// The event name can be found in the above query
this.getLivingList();
});
this.player[this.player.length - 1].on('error', () => {
// The event name can be found in the above query
this.getLivingList();
});
},
// Page turning operation
currentChange(e) {
this.closePlayer();
this.pageno = e;
this.getLivingList();
},
// Get the list in live broadcast
async getLivingList() {
let res = await this.$req(api.liveShowers, {
...this.searchForm,
pageno: this.pageno - 1,
pagesize: this.pagesize,
});
console.log(res);
if (res.code == 200) {
// Get the data, assign the value, and then loop instantiate it
res.data.showers.push(res.data.showers[0]);
res.data.showers.push(res.data.showers[0]);
res.data.showers.push(res.data.showers[0]);
res.data.showers.push(res.data.showers[0]);
this.livingList = res.data.showers;
this.totalP = res.data.total_page - 0;
this.totalS = res.data.total_showers;
this.isrefresh = false;
if (this.livingList.length > 0) {
setTimeout(() => {
this.livingList.forEach((item, idx) => {
let domid = 'videos' + idx;
this.initPlayer(
domid,
item.play_url,
this.$store.state.coverTop + item.showcover
);
});
}, 400);
} else {
// If there is no live data returned, it is not the first 1 Page. Just jump to number one 1 Page rerequest 1 Under
if (this.pageno > 1) {
this.pageno = 1;
this.getLivingList();
}
}
}
},
Summarize