File size: 2,368 Bytes
bca4ff8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
// part of script inspired by https://github.com/addpipe/simple-recorderjs-demo
var gumStream; 						//stream from getUserMedia()
var rec; 							//Recorder.js object
var input; 							//MediaStreamAudioSourceNode we'll be recording

// shim for AudioContext when it's not avb. 
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext; //audio context to help us record
const resultNode = document.getElementById('result');
const actionButton = document.getElementById('action');

function resultProcess(data) {
    resultNode.textContent = `Довжина тексту: ${data.length} \n
        Текст: ${data}
    `;
    actionButton.textContent = "Start recording (3 sec)";
    actionButton.disabled = false;
}

function exportWAV(blob) {
    var data = new FormData()
    data.append('file', blob);
    fetch(`./recognize`, { method: "POST", body: data })
        .then(response => response.text())
        .then(resultProcess);
}
function record() {

    var constraints = { audio: true, video: false }
    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        actionButton.textContent = "Recording..."
        actionButton.disabled = true;
        /*
            create an audio context after getUserMedia is called
            sampleRate might change after getUserMedia is called, like it does on macOS when recording through AirPods
            the sampleRate defaults to the one set in your OS for your playback device
        */
        audioContext = new AudioContext();

        /*  assign to gumStream for later use  */
        gumStream = stream;

        /* use the stream */
        input = audioContext.createMediaStreamSource(stream);

        /* 
            Create the Recorder object and configure to record mono sound (1 channel)
            Recording 2 channels  will double the file size
        */
        rec = new Recorder(input, { numChannels: 1 })

        //start the recording process
        rec.record()
        sleep(3000).then(stop);
    })
}


function stop() {
    rec.stop();

    //stop microphone access
    gumStream.getAudioTracks()[0].stop();

    //create the wav blob and pass it on to createDownloadLink
    rec.exportWAV(exportWAV);
}


const sleep = time => new Promise(resolve => setTimeout(resolve, time));

async function handleAction() {
    record();
}