当前位置: 欣欣网 > 码农

WebRTC实战教程:如何录制视频和播放

2024-03-07码农

💻 在线演示

演示地址 https://webrtc.tinywan.com/docs-2022/demo-05/index.html

摄像头申请

拍照截图

📝 源码

index.html

<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>WebRTC实战教程:如何录制视频和播放</title>
</head>
<body>
<h1>WebRTC实战教程:如何录制视频和播放</h1>
<divid="app">
<div>
<videoref="preview"width="200"height="150"autoplay></video>
</div>
<div>
<button @click="btnRecordClicked">录制</button>
<button @click="btnPauseClicked">暂停</button>
<button @click="btnResumeClicked">重新录制</button>
<button @click="btnStopClicked">停止</button>
<button @click="btnPlayerClicked">播放</button>
</div>
<div>
<videoref="player"autoplaycontrolswidth="400"height="300"></video>
</div>
</div>
<scriptsrc="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
<scriptsrc="main.js"></script>
</body>
</html>

main.js

const App = {
data() {
return {
currentWebmDatanull,
}
},
mounted() {
this._initDevice();
},
methods: {
async _initDevice (){
this._stream = await navigator.mediaDevices.getUserMedia({video:true,audio:false});
this.$refs.preview.srcObject = this._stream;
this._recorder = new MediaRecorder(this._stream, {mimeType:"video/webm;codes=h264"});
this._recorder.ondataavailable = this.recorderDataAvailableHandle.bind(this)
},
recorderDataAvailableHandle(e){
this.currentWebmData = e.data;
},
btnRecordClicked(){
this._recorder.start();
},
btnPauseClicked(){
this._recorder.pause();
},
btnResumeClicked(){
this._recorder.resume();
},
btnStopClicked(){
this._recorder.stop();
},
btnPlayerClicked(){
this.$refs.player.src = URL.createObjectURL(this.currentWebmData);
}
}
};
var vm = Vue.createApp(App).mount('#app');