使用 navigator.mediaDevices.getDisplayMedia() 来完成屏幕共享!
使用 MediaRecorder 实例完成屏幕录制!

效果预览

开发阶段

创建 .vue文件,代码内容如下:

  1. template
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <template>
    <div class="shared-screen">
    <video id="video" autoplay playsinline muted width="100%" height="500"></video>

    <div class="operation" style="text-align: center">
    <el-button type="primary" @click="sharedScreen">共享屏幕</el-button>
    <el-button type="success" @click="startMediaRecorder">开始录制</el-button>
    <el-button type="danger" @click="stopMediaRecorder">停止录制</el-button>
    </div>

    </div>
    </template>
  2. script
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    <script>
    import {downloadFile} from "@/utils";

    export default {
    name: "index",
    data(){
    return {
    mediaRecorder: null
    }
    },
    methods:{
    async sharedScreen() {
    console.log('navigator.mediaDevices', navigator.mediaDevices)
    // 提示用户授权捕获窗口内容
    let localStream = await navigator.mediaDevices.getDisplayMedia({
    audio: true,
    video: true
    })
    // 播放共享屏幕
    this.playStream( localStream )
    // 准备录制
    this.getMediaStream( localStream )
    },
    // 共享窗口
    playStream( stream ){
    const video = document.querySelector('#video');
    console.log('playStream', video)
    // 将 stream 流 放置 video 视频窗口
    video.srcObject = stream
    },
    // 准备录制
    getMediaStream( stream ){
    // MediaRecorder api 对 mimeType 参数的支持是[有限的]
    // webm 是 Google 专门为 web 端推出的一种视频格式。100% 开源,
    // 且 100%兼容 Google Chrome 浏览器和 Android 设备
    const options = {
    // 音频、视频的码率
    audioBitsPerSecond: 128000,
    videoBitsPerSecond: 2500000,
    mimeType:"video/webm"
    }
    // MediaRecorder 用于录制媒体流的 API, 将录制的数据保存成一个文件
    this.mediaRecorder = new MediaRecorder(stream, options)
    },
    // 开始录制
    startMediaRecorder(){
    if (this.mediaRecorder) {
    this.mediaRecorder.start()
    // 录制监听
    this.mediaRecorder.onstart = () => {
    console.log('开始录制!')
    }
    // 当有可用数据
    this.mediaRecorder.ondataavailable = (e) => {
    const blobObj = new Blob([e.data], { type: 'video/mp4' })
    downloadFile(blobObj, 'Recording.mp4')
    }
    }
    },
    // 停止录制
    stopMediaRecorder(){
    if (this.mediaRecorder) {
    console.log('停止录制!')
    this.mediaRecorder.stop()
    }
    }
    }
    }
    </script>