js get mic level

Solutions on MaxInterview for js get mic level by the best coders in the world

showing results for - "js get mic level"
Giulio
18 May 2019
1/**
2 * Create global accessible variables that will be modified later
3 */
4var audioContext = null;
5var meter = null;
6var rafID = null;
7var mediaStreamSource = null;
8
9// Retrieve AudioContext with all the prefixes of the browsers
10window.AudioContext = window.AudioContext || window.webkitAudioContext;
11
12// Get an audio context
13audioContext = new AudioContext();
14
15/**
16 * Callback triggered if the microphone permission is denied
17 */
18function onMicrophoneDenied() {
19    alert('Stream generation failed.');
20}
21
22/**
23 * Callback triggered if the access to the microphone is granted
24 */
25function onMicrophoneGranted(stream) {
26    // Create an AudioNode from the stream.
27    mediaStreamSource = audioContext.createMediaStreamSource(stream);
28    // Create a new volume meter and connect it.
29    meter = createAudioMeter(audioContext);
30    mediaStreamSource.connect(meter);
31
32    // Trigger callback that shows the level of the "Volume Meter"
33    onLevelChange();
34}
35
36/**
37 * This function is executed repeatedly
38 */
39function onLevelChange(time) {
40    // check if we're currently clipping
41
42    if (meter.checkClipping()) {
43        console.warn(meter.volume);
44    } else {
45        console.log(meter.volume);
46    }
47
48    // set up the next callback
49    rafID = window.requestAnimationFrame(onLevelChange);
50}
51
52
53// Try to get access to the microphone
54try {
55
56    // Retrieve getUserMedia API with all the prefixes of the browsers
57    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
58
59    // Ask for an audio input
60    navigator.getUserMedia(
61        {
62            "audio": {
63                "mandatory": {
64                    "googEchoCancellation": "false",
65                    "googAutoGainControl": "false",
66                    "googNoiseSuppression": "false",
67                    "googHighpassFilter": "false"
68                },
69                "optional": []
70            },
71        },
72        onMicrophoneGranted,
73        onMicrophoneDenied
74    );
75} catch (e) {
76    alert('getUserMedia threw exception :' + e);
77}