How encapsulate to the function navigator.mediaDevices.getUserMedia?

28 views Asked by At

I am creating an object to encapsulate the navigator.mediaDevices object.

Here is my Object code:

    class LocalStreamManager {
    static #templateConstraint = {
        "audio": {
            channelCount: 2,
            echoCancellation: true,
            sampleSize: 16
        },
        "video": {
            width: { min: "640", ideal: "1280", max: "1920" },
            height: { min: "480", ideal: "720", max: "1080" }
        }
    };
    /**
     * Get client media stream
     * @date 8/18/2023 - 1:45:00 PM
     *
     * @async
     * @param {boolean} shareVideo if true include video stream in return stream, else do not.
     * @param {boolean} shareAudio if true include audio stream in return stream, else do not.
     * @returns {MediaStream}
     * @static 
     */
    static async getMediaStream(shareVideo, shareAudio) {
        let constraints = {};
        if (shareVideo) {
            constraints["video"] = this.#templateConstraint.video;
        }
        if (shareAudio) {
            constraints["audio"] = this.#templateConstraint.audio;
        }
        console.log("constraints=" + JSON.stringify(constraints));
        if (shareVideo || shareAudio) {
            return await navigator.mediaDevices.getUserMedia(constraints);
        } else {
            return null;
        }
    }
  .........................   
}

Here is the caller code:

    let localStream;
    try {
        localStream = await LocalStreamManager.getMediaStream(isShareVideo, isShareAudio);
    } catch (error) {
        console.log("Get Media Stream failure:" + error.message);
        localStream = null;
    } 

In the Visual Studio Code editor, it prompts the "await" in the following statement has no effect.

        localStream = await LocalStreamManager.getMediaStream(isShareVideo, isShareAudio);

enter image description here

How can I remove the prompt?

I have tried to modify the LocalStreamManager.getMediaStream as below:

static async getMediaStream(shareVideo, shareAudio) {
    let constraints = {};
    if (shareVideo) {
        constraints["video"] = this.#templateConstraint.video;
    }
    if (shareAudio) {
        constraints["audio"] = this.#templateConstraint.audio;
    }
    return await navigator.mediaDevices.getUserMedia(constraints);
}

However, the prompt still exists.

1

There are 1 answers

0
The KNVB On

The solution is to change the JSDOC from:

 @returns {MediaStream}

to

 @returns {Promise<MediaStream?>}

thank you, Jaromanda X