利用原生的post请求去获取视频流(播放插件flv.js)
前端新手,记录借鉴,不喜勿喷
需求:利用code去获取视频流,在播放器播放
gitee连接: https://gitee.com/nancyfish/video-display-demo.
npm install flv.js
第一步:通过ref获取播放组件的getSteam方法(获取视频流的方法)
<template>
<div class="home">
<HelloWorld ref="getinit" />
</div>
</template>
<script>
import HelloWorld from "@/components/HelloWorld.vue";
export default {
name: "Home",
components: {
HelloWorld
},
mounted() {
this.$refs.getinit.init();
}
};
</script>
第二步:在组件里写入播放标签
<template>
<div class="hello">
<video src id="video_play" controls autoplay muted class="video"></video>
</div>
</template>
第三步:数据请求 —直接上代码
data() {
return {
players: []
};
},
methods: {
init() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://10.195.254.203:18590/video/live/getPlayUrl");
xhr.setRequestHeader("content-type", "application/json");
xhr.onload = () => {
// console.log(xhr.status, "888888"); // 200
if (xhr.status == 200) {
console.log(JSON.parse(xhr.response), "拿到的结果数据");
const videoElement = document.getElementById("video_play");
if (videoElement && FlvJs.isSupported()) {
const flvPlayer = FlvJs.createPlayer({
type: "flv",
url: JSON.parse(xhr.response).data.wsUrl,
isLive: true,
hasAudio: true,
hasVideo: true
});
this.players.push(flvPlayer); //保存flv
flvPlayer.attachMediaElement(videoElement);
flvPlayer.load();
try {
flvPlayer.play();
} catch (error) {
// this.$message.warning('您的浏览器不支持自动播放视频,请点击播放按钮!');
}
}
}
};
xhr.send(
JSON.stringify({
deviceCode: "34020000001110000001",
channelCode: "34020000001320000002"
})
);
}
}
这样打开浏览器就可以看到了啦