如何使用音訊輸入數據流
語音 SDK 提供將音訊串流至辨識器的方式,作為麥克風或檔案輸入的替代方案。
本指南說明如何使用音訊輸入資料流。 同時描述音訊輸入資料流的一些需求與限制。
請參閱 GitHub 上使用音訊輸入串流進行語音轉換文字辨識的更多範例。
識別音訊資料流的格式
識別音訊數據流的格式。
支援的音訊範例如下:
- PCM 格式 (int-16、帶正負號的)
- 一個通道
- 每個樣本 16 位、每秒 8,000 或 16,000 個樣本(每秒 16,000 個字節或每秒 32,000 個字節)
- 雙區塊對齊(16 位,包括樣本填補)
SDK 中建立音訊格式的對應程式代碼看起來像下列範例:
byte channels = 1;
byte bitsPerSample = 16;
int samplesPerSecond = 16000; // or 8000
var audioFormat = AudioStreamFormat.GetWaveFormatPCM(samplesPerSecond, bitsPerSample, channels);
請確定您的程式代碼會根據這些規格提供RAW音訊數據。 此外,請確定 16 位樣本會以小端格式抵達。 如果您的音訊源數據不符合支援的格式,則必須將音訊轉碼為所需的格式。
建立自己的音訊輸入資料流類別
建立自己衍生自 PullAudioInputStreamCallback
的音訊輸入資料流類別。 實作 Read()
和 Close()
成員。 確切的函式簽章與語言相關,但程式代碼看起來類似下列程式代碼範例:
public class ContosoAudioStream : PullAudioInputStreamCallback
{
public ContosoAudioStream() {}
public override int Read(byte[] buffer, uint size)
{
// Returns audio data to the caller.
// E.g., return read(config.YYY, buffer, size);
return 0;
}
public override void Close()
{
// Close and clean up resources.
}
}
根據您的音訊格式與自訂音效輸入資料流,建立音訊設定。 例如:
var audioConfig = AudioConfig.FromStreamInput(new ContosoAudioStream(), audioFormat);
以下說明如何在語音辨識器內容中使用自訂音訊輸入資料流:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
public class ContosoAudioStream : PullAudioInputStreamCallback
{
public ContosoAudioStream() {}
public override int Read(byte[] buffer, uint size)
{
// Returns audio data to the caller.
// E.g., return read(config.YYY, buffer, size);
return 0;
}
public override void Close()
{
// Close and clean up resources.
}
}
class Program
{
static string speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY");
static string speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION");
async static Task Main(string[] args)
{
byte channels = 1;
byte bitsPerSample = 16;
uint samplesPerSecond = 16000; // or 8000
var audioFormat = AudioStreamFormat.GetWaveFormatPCM(samplesPerSecond, bitsPerSample, channels);
var audioConfig = AudioConfig.FromStreamInput(new ContosoAudioStream(), audioFormat);
var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
speechConfig.SpeechRecognitionLanguage = "en-US";
var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);
Console.WriteLine("Speak into your microphone.");
var speechRecognitionResult = await speechRecognizer.RecognizeOnceAsync();
Console.WriteLine($"RECOGNIZED: Text={speechRecognitionResult.Text}");
}
}
下一步
意見反映
https://aka.ms/ContentUserFeedback。
即將推出:我們會在 2024 年淘汰 GitHub 問題,並以全新的意見反應系統取代並作為內容意見反應的渠道。 如需更多資訊,請參閱:提交及檢視以下的意見反映: