適用於 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 範例存放庫中找到更多範例。