使用 WebSockets 轉錄音訊檔案(Node.js)
此示例顯示如何使用 IBM Watson Speech to Text 服務識別音訊檔案的型別,並在該檔案中生成語音文字的轉錄。
此示例需要 Speech to Text 服務憑據和 Node.js
- 為 Watson Developer Cloud Node.js SDK 安裝 npm 模組 :
$ npm install watson-developer-cloud
- 建立一個 JavaScript 檔案(例如, app.js )並將以下程式碼複製到其中。確保為 Speech to Text 服務例項輸入
username
和password
。
var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1');
var fs = require('fs');
var speech_to_text = new SpeechToTextV1({
username: 'INSERT YOUR USERNAME FOR THE SERVICE HERE',
password: 'INSERT YOUR PASSWORD FOR THE SERVICE HERE',
url: 'https://stream.watsonplatform.net/speech-to-text/api'
});
var params = {
content_type: 'audio/flac'
};
// Create the stream,
var recognizeStream = speech_to_text.createRecognizeStream(params);
// pipe in some audio,
fs.createReadStream('0001.flac').pipe(recognizeStream);
// and pipe out the transcription.
recognizeStream.pipe(fs.createWriteStream('transcription.txt'));
// To get strings instead of Buffers from received `data` events:
recognizeStream.setEncoding('utf8');
// Listen for 'data' events for just the final text.
// Listen for 'results' events to get the raw JSON with interim results, timings, etc.
['data', 'results', 'error', 'connection-close'].forEach(function(eventName) {
recognizeStream.on(eventName, console.log.bind(console, eventName + ' event: '));
});
-
將示例音訊檔案 0001.flac 儲存到同一目錄。此示例程式碼設定為處理 FLAC 檔案,但你可以修改示例程式碼的
params
部分以從其他格式的音訊檔案獲取轉錄。支援的格式包括 WAV (型別audio/wav
), OGG (型別audio/ogg
)等。有關完整列表,請參閱 Speech to Text API 參考 。 -
執行應用程式(使用包含示例程式碼的檔案的名稱)
$ node app.js
執行應用程式後,你將在執行應用程式的目錄中的檔案 transcription.txt 中找到音訊檔案中的轉錄文字。