你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
用于 JavaScript 的认知服务语音 SDK
概述
为了简化支持语音的应用程序的开发,Microsoft 提供了用于 语音服务的语音 SDK。 语音 SDK 提供一致的本机语音转文本和语音翻译 API。
安装 npm 模块
安装认知服务语音 SDK npm 模块
npm install microsoft-cognitiveservices-speech-sdk
示例
以下代码片段演示如何从文件中进行简单的语音识别:
// Pull in the required packages.
var sdk = require("microsoft-cognitiveservices-speech-sdk");
var fs = require("fs");
// Replace with your own subscription key, service region (e.g., "westus"), and
// the name of the file you want to run through the speech recognizer.
var subscriptionKey = "YourSubscriptionKey";
var serviceRegion = "YourServiceRegion"; // e.g., "westus"
var filename = "YourAudioFile.wav"; // 16000 Hz, Mono
// Create the push stream we need for the speech sdk.
var pushStream = sdk.AudioInputStream.createPushStream();
// Open the file and push it to the push stream.
fs.createReadStream(filename).on('data', function(arrayBuffer) {
pushStream.write(arrayBuffer.buffer);
}).on('end', function() {
pushStream.close();
});
// We are done with the setup
console.log("Now recognizing from: " + filename);
// Create the audio-config pointing to our stream and
// the speech config specifying the language.
var audioConfig = sdk.AudioConfig.fromStreamInput(pushStream);
var speechConfig = sdk.SpeechConfig.fromSubscription(subscriptionKey, serviceRegion);
// Setting the recognition language to English.
speechConfig.speechRecognitionLanguage = "en-US";
// Create the speech recognizer.
var recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
// Start the recognizer and wait for a result.
recognizer.recognizeOnceAsync(
function (result) {
console.log(result);
recognizer.close();
recognizer = undefined;
},
function (err) {
console.trace("err - " + err);
recognizer.close();
recognizer = undefined;
});
前面的示例使用单次识别,该识别可识别单个言语。 还可以使用 连续识别 来控制何时停止识别。 有关更多选项,请查看我们的 分步快速入门 。
示例
- 适用于 JavaScript 的分步快速入门。
- 适用于浏览器的分步快速入门。
- 在语音 SDK 示例存储库中可找到更多示例。