js录屏下载为mp4本地播放导出file

摘要:其实浏览器自身也是可以录制mp4的,只是很多人不知道,无从下手,特别是遇到相关需求的时候不知道怎么操作;下面是实战后总结的方法,直接拿取就可以使用。

封装录屏方法
export class ScreenRecording {
    mediaRecorder: MediaRecorder | null; // 录音对象
    stream: MediaStream | null; // 轨道对象
    chunks: any[]; // 录音缓存
    endCallback: any[]; // 录音结束回调
    constructor() {
        this.mediaRecorder = null;
        this.stream = null;
        this.chunks = [];
        this.endCallback = [];
    }
    create() { // 创建
        return new Promise((resolve, reject) => {
            this.resetState();
            navigator.mediaDevices.getDisplayMedia({ video: true, audio: true }).then((stream) => {
                this.stream = stream;
                const mime = MediaRecorder.isTypeSupported("video/webm\;codecs=h264") ? "video/webm\;codecs=h264" : "video/webm";
                this.mediaRecorder = new MediaRecorder(stream, { mimeType: mime });
                resolve({code: 1, message: '创建成功'});
            }).catch((err) => {
                reject(err);
            });
        });
    }
    start() { // 开始
        return new Promise((resolve, reject) => {
            this.judgeMediaRecorderIs().then((mediaRecorder: MediaRecorder) => {
                // start(100); 每100毫秒生成一个数据可用事件
                mediaRecorder.start();
                // 完成一次录制片段后触发
                mediaRecorder.addEventListener('dataavailable', (e) => {
                    this.chunks.push(e.data);
                });
                resolve({code: 1, message: '开始录制'});
            }).catch((err) => {
                reject(err);
            });
        });
    }
    stop() { // 结束
        return new Promise((resolve, reject) => {
            this.judgeMediaRecorderIs().then((mediaRecorder: MediaRecorder) => {
                if (mediaRecorder.state === 'inactive') {
                    return reject({code: 0, message: '已结束'});
                };
                mediaRecorder.stop();
                this.stream.getTracks().forEach((track) => { track.stop(); });
                // 监听结束录制
                mediaRecorder.addEventListener('stop', (e: any) => {
                	resolve({code: 1, message:'录制结束'});
                    // 如果有录制结束回调的的话,执行回调
                    this.endCallback.forEach((callback) => {
                        callback();
                        this.endCallback.shift();
                    });
                });
            }).catch((err) => {
                reject(err);
            });
        });
    }
    download() { // 下载
        return new Promise((resolve, reject) => {
            this.handleChunksToBolb().then((blob: Blob) => {
                let url = URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = url;
                a.download = MediaRecorder.isTypeSupported("video/webm\;codecs=h264") ? 'video.mp4' : 'video.webm';
                a.click();
                resolve(url);
            }).catch((err) => {
                reject(err);
            });
        });
    }
    viewRecording() { // 预览播放
        return new Promise((resolve, reject) => {
            this.handleChunksToBolb().then((blob: Blob) => {
                let url = URL.createObjectURL(blob);
                resolve(url);
            }).catch((err) => {
                reject(err);
            });
        });
    }
    toFile() { // 转file
        return new Promise((resolve, reject) => {
            this.handleChunksToBolb().then((blob: Blob) => {
                let filename = MediaRecorder.isTypeSupported("video/webm\;codecs=h264") ? 'video.mp4' : 'video.webm';
                let fileType = filename.includes('.mp4') ? 'video/mp4' : 'video/webm';
                resolve(new File([blob], filename, { type: fileType }));
            }).catch((err) => {
                reject(err);
            });
        });
    }
    handleChunksToBolb() { // 转bolb
        return new Promise((resolve, reject) => {
            this.judgeChunksIs().then((chunks: any) => {
                let blob = new Blob(chunks, { type: MediaRecorder.isTypeSupported("video/webm\;codecs=h264") ? 'video/mp4' : chunks[0].type })
                resolve(blob);
            }).catch((err) => {
                reject(err);
            });
        });
    }
    judgeChunksIs() { // 判断是否有录音缓存
        return new Promise((resolve, reject) => {
            let chunks = this.chunks;
            if (chunks.length === 0) {
                return reject({code: 0, message: '没有录制的缓冲'});
            };
            return resolve(chunks);
        });
    }
    judgeMediaRecorderIs() { // 判断是否创建了录制对象
        return new Promise((resolve, reject) => {
            let mediaRecorder = this.mediaRecorder;
            if (!mediaRecorder) { return reject({code: 0, message: '请先创建一个录制对象'}); };
            resolve(mediaRecorder);
        });
    }
    setEndCallback(callback) { // 存结束回调
        this.endCallback.push(callback);
    }
    resetState() { // 初始化状态
        this.chunks = [];
        this.mediaRecorder = null;
        this.stream = null;
    }
};
录屏方法使用
let myScreenRecording = new ScreenRecording();
/* @params res: {
    format: 'mp4',  type: String; value: 'mp4' | 'webm'; 说明:当前支持的录制格式;
} */
myScreenRecording.create().then((res: {format: 'mp4'}) => {
    // 开始录制
    myScreenRecording.start();
    // 因为录屏用户用户可能自己取消,而不是点击按钮取消所以新建一个回调函数作为监听
    let endRecording = () => {
        // 下载到本地
        myScreenRecording.download();
        // 本地播放url
        myScreenRecording.viewRecording().then((srcObject) => {});
        // 转file可上传到后台服务器
        myScreenRecording.toFile().then((file) => {});
    };
    // 存结束录音回调函数
    myScreenRecording.setEndCallback(endRecording);
});
// 手动结束录屏,then后才可以下载、获取本地播放url、转file对象
myScreenRecording.stop().then(() => {});

你可能感兴趣的:(WebRtc,javascript,webrtc)