首页 > 解决方案 > 在方法内声明空数组变量

问题描述

我正在创建类以使用 getUserMedia。在方法内部startRecording(),我试图声明/重新声明一个空数组this.recordedBlobs = [];,该数组应该保存来自媒体流的记录数据。数据应该this.mediaRecorder.ondataavailable通过调用方法添加到事件中this.handleDataAvailable。但this.handleDataAvailable不断抛出错误

Uncaught ReferenceError: recordedBlobs is not defined
at MediaRecorder.handleDataAvailable

类的整个部分如下所示:

startRecording() {
    this.snapshotButton.disabled = true;
    this.sendButton.disabled = true;
    this.stopButton.disabled = false;
    this.recordButton.textContent = 'Pause';

    this.recordedBlobs = [];
    let options = {mimeType: 'video/webm;codecs=vp9'};
    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        console.error(`${options.mimeType} is not Supported`);
        options = {mimeType: 'video/webm;codecs=vp8'};
        if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            console.error(`${options.mimeType} is not Supported`);
            options = {mimeType: 'video/webm'};
            if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                console.error(`${options.mimeType} is not Supported`);
                options = {mimeType: ''};
            }
        }
    }
    try {
        this.mediaRecorder = new MediaRecorder(window.stream, options);
    } catch (e) {
        console.error('Exception while creating MediaRecorder:', e);
        return;
    }

    console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options);
    this.mediaRecorder.onstop = (event) => {
        console.log('Recorder stopped: ', event);
    };
    this.mediaRecorder.ondataavailable = this.handleDataAvailable;
    this.mediaRecorder.start(10); // collect 10ms of data
    console.log('MediaRecorder started', this.mediaRecorder);
    return this.recordedBlobs;
}
stopRecording() {
    this.mediaRecorder.stop();
    this.recordButton.textContent = 'Start';
    this.snapshotButton.disabled = false;
    this.sendButton.disabled = false;
    this.sendButton.textContent = 'Send Video';
    this.stopButton.disabled = true;
    console.log('Recorded Blobs: ', this.recordedBlobs);
}
handleDataAvailable(event) {
    if (event.data && event.data.size > 0) {
        this.recordedBlobs.push(event.data);
    }
}

有谁知道为什么handleDataAvailable不能访问this.recordedBlobs。非常感谢任何帮助。

这是构造函数:

constructor(button, constraints) {
    this.constraints = constraints;
    this.openVideoPanelButton = document.querySelector(button);
    this.openVideoPanelButton.addEventListener('click', async () => {
        this.openVideoPanel();
    });
    console.log('initialized');
}

它并不是真正重复的,因为handleDataAvailable()我可以访问内部方法,this但它的值this仅包含 MediaRecorder 对象

标签: javascript

解决方案


在构造方法中尝试用空数组初始化

constructor(){
    this.recordedBlobs = [];
}

推荐阅读