首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过socket.io将浏览器中的实时音频传输到Google语音?

如何通过socket.io将浏览器中的实时音频传输到Google语音?
EN

Stack Overflow用户
提问于 2018-06-21 19:18:11
回答 1查看 8.1K关注 0票数 14

我有一个基于反应的应用程序的情况,我有一个输入,我想让语音输入以及。我可以只与Chrome和Firefox兼容,所以我考虑使用getUserMedia。我知道我会用Google的演讲来给API发短信。不过,我有几个注意事项:

  1. 我希望这个能实时传输我的音频数据,而不仅仅是在我结束录音的时候。这意味着,我发现的许多解决方案都不能很好地工作,因为保存文件并将其发送到Google语音是不够的。
  2. 我不相信我的前端有我的Google信息。相反,我已经在后端运行了一项服务,它具有我的凭据,我想将音频(实时)流到后端,然后从后端流到Google Cloud,然后在返回到前端时向我的记录发送更新。
  3. 我已经使用socket.io连接到那个后端服务,我希望完全通过套接字来管理它,而不必使用Binary.js或任何类似的东西。

似乎没有任何地方有关于如何做到这一点的好教程。我做什么好?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-21 19:18:11

第一,信用到期的地方:我在这里的解决方案中有很大一部分是通过引用vin的谷歌-云-演讲-节点-套接字-游乐场项目来创建的。然而,我不得不在我的React应用程序中修改这部分内容,所以我将分享一些我所做的更改。

我在这里的解决方案由四个部分组成,两个在前端,两个在后端。

我的前端解决方案分为两部分:

  1. 一个实用程序文件,用于访问我的麦克风、将音频流到后端、从后端检索数据、每次从后端接收数据时运行回调函数,然后在完成流处理或后端抛出错误时清除其自身。
  2. 一个麦克风组件包装了我的反应功能。

我的后端解决方案分为两部分:

  1. 处理实际语音识别流的实用文件。
  2. 我的main.js文件

(这些文件不需要以任何方式分开;我们的main.js文件已经是一个没有它的庞然大物了。)

我的大部分代码将被摘录出来,但是我的实用程序将被完整地显示出来,因为我在所有涉及的阶段中都有很多问题。我的前端实用程序文件如下所示:

代码语言:javascript
复制
// Stream Audio
let bufferSize = 2048,
    AudioContext,
    context,
    processor,
    input,
    globalStream;

//audioStream constraints
const constraints = {
    audio: true,
    video: false
};

let AudioStreamer = {
    /**
     * @param {function} onData Callback to run on data each time it's received
     * @param {function} onError Callback to run on an error if one is emitted.
     */
    initRecording: function(onData, onError) {
        socket.emit('startGoogleCloudStream', {
            config: {
                encoding: 'LINEAR16',
                sampleRateHertz: 16000,
                languageCode: 'en-US',
                profanityFilter: false,
                enableWordTimeOffsets: true
            },
            interimResults: true // If you want interim results, set this to true
        }); //init socket Google Speech Connection
        AudioContext = window.AudioContext || window.webkitAudioContext;
        context = new AudioContext();
        processor = context.createScriptProcessor(bufferSize, 1, 1);
        processor.connect(context.destination);
        context.resume();

        var handleSuccess = function (stream) {
            globalStream = stream;
            input = context.createMediaStreamSource(stream);
            input.connect(processor);

            processor.onaudioprocess = function (e) {
                microphoneProcess(e);
            };
        };

        navigator.mediaDevices.getUserMedia(constraints)
            .then(handleSuccess);

        // Bind the data handler callback
        if(onData) {
            socket.on('speechData', (data) => {
                onData(data);
            });
        }

        socket.on('googleCloudStreamError', (error) => {
            if(onError) {
                onError('error');
            }
            // We don't want to emit another end stream event
            closeAll();
        });
    },

    stopRecording: function() {
        socket.emit('endGoogleCloudStream', '');
        closeAll();
    }
}

export default AudioStreamer;

// Helper functions
/**
 * Processes microphone data into a data stream
 * 
 * @param {object} e Input from the microphone
 */
function microphoneProcess(e) {
    var left = e.inputBuffer.getChannelData(0);
    var left16 = convertFloat32ToInt16(left);
    socket.emit('binaryAudioData', left16);
}

/**
 * Converts a buffer from float32 to int16. Necessary for streaming.
 * sampleRateHertz of 1600.
 * 
 * @param {object} buffer Buffer being converted
 */
function convertFloat32ToInt16(buffer) {
    let l = buffer.length;
    let buf = new Int16Array(l / 3);

    while (l--) {
        if (l % 3 === 0) {
            buf[l / 3] = buffer[l] * 0xFFFF;
        }
    }
    return buf.buffer
}

/**
 * Stops recording and closes everything down. Runs on error or on stop.
 */
function closeAll() {
    // Clear the listeners (prevents issue if opening and closing repeatedly)
    socket.off('speechData');
    socket.off('googleCloudStreamError');
    let tracks = globalStream ? globalStream.getTracks() : null; 
        let track = tracks ? tracks[0] : null;
        if(track) {
            track.stop();
        }

        if(processor) {
            if(input) {
                try {
                    input.disconnect(processor);
                } catch(error) {
                    console.warn('Attempt to disconnect input failed.')
                }
            }
            processor.disconnect(context.destination);
        }
        if(context) {
            context.close().then(function () {
                input = null;
                processor = null;
                context = null;
                AudioContext = null;
            });
        }
}

这段代码的主要要点(除了getUserMedia配置本身有点不稳定)是,处理器的onaudioprocess回调将数据转换为Int16后将speechData事件发送到套接字。我对上面链接引用的主要更改是替换所有功能,以便使用回调函数(由我的React组件使用)实际更新DOM,并添加一些源代码中没有包含的错误处理。

然后,我只需使用以下命令就可以在我的React组件中访问该组件:

代码语言:javascript
复制
onStart() {
    this.setState({
        recording: true
    });
    if(this.props.onStart) {
        this.props.onStart();
    }
    speechToTextUtils.initRecording((data) => {
        if(this.props.onUpdate) {
            this.props.onUpdate(data);
        }   
    }, (error) => {
        console.error('Error when recording', error);
        this.setState({recording: false});
        // No further action needed, as this already closes itself on error
    });
}

onStop() {
    this.setState({recording: false});
    speechToTextUtils.stopRecording();
    if(this.props.onStop) {
        this.props.onStop();
    }
}

(我将实际的数据处理程序作为这个组件的支柱传递给它)。

然后在后端,我的服务在main.js中处理了三个主要事件

代码语言:javascript
复制
// Start the stream
            socket.on('startGoogleCloudStream', function(request) {
                speechToTextUtils.startRecognitionStream(socket, GCSServiceAccount, request);
            });
            // Receive audio data
            socket.on('binaryAudioData', function(data) {
                speechToTextUtils.receiveData(data);
            });

            // End the audio stream
            socket.on('endGoogleCloudStream', function() {
                speechToTextUtils.stopRecognitionStream();
            });

然后,我的speechToTextUtils看起来像:

代码语言:javascript
复制
// Google Cloud
const speech = require('@google-cloud/speech');
let speechClient = null;

let recognizeStream = null;

module.exports = {
    /**
     * @param {object} client A socket client on which to emit events
     * @param {object} GCSServiceAccount The credentials for our google cloud API access
     * @param {object} request A request object of the form expected by streamingRecognize. Variable keys and setup.
     */
    startRecognitionStream: function (client, GCSServiceAccount, request) {
        if(!speechClient) {
            speechClient = new speech.SpeechClient({
                projectId: 'Insert your project ID here',
                credentials: GCSServiceAccount
            }); // Creates a client
        }
        recognizeStream = speechClient.streamingRecognize(request)
            .on('error', (err) => {
                console.error('Error when processing audio: ' + (err && err.code ? 'Code: ' + err.code + ' ' : '') + (err && err.details ? err.details : ''));
                client.emit('googleCloudStreamError', err);
                this.stopRecognitionStream();
            })
            .on('data', (data) => {
                client.emit('speechData', data);

                // if end of utterance, let's restart stream
                // this is a small hack. After 65 seconds of silence, the stream will still throw an error for speech length limit
                if (data.results[0] && data.results[0].isFinal) {
                    this.stopRecognitionStream();
                    this.startRecognitionStream(client, GCSServiceAccount, request);
                    // console.log('restarted stream serverside');
                }
            });
    },
    /**
     * Closes the recognize stream and wipes it
     */
    stopRecognitionStream: function () {
        if (recognizeStream) {
            recognizeStream.end();
        }
        recognizeStream = null;
    },
    /**
     * Receives streaming data and writes it to the recognizeStream for transcription
     * 
     * @param {Buffer} data A section of audio data
     */
    receiveData: function (data) {
        if (recognizeStream) {
            recognizeStream.write(data);
        }
    }
};

(同样,您并不严格地需要这个util文件,您当然可以将speechClient作为一个const放在文件的顶部,这取决于您如何获得凭据;这正是我实现它的方式。)

最后,这应该足以让你开始做这件事。我鼓励您在重用或修改代码之前尽力理解它,因为它可能不会对您“开箱即用”,但与我发现的所有其他来源不同,这至少会让您在项目的所有相关阶段开始。我希望这个答案能防止别人像我一样受苦。

票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50976084

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档