使用語音轉文字 API

已完成

小提示

有關更多詳細信息,請參閱 文本和圖像 選項卡!

Foundry 工具中的 Azure 語音支援透過語音轉文字 API 進行語音辨識。 雖然特定詳細數據有所不同,但視所使用的 SDK 而定(Python、C#等等):使用 語音轉換文字 API 有一致的模式:

圖示顯示由 SpeechConfig 和 AudioConfig 建立的語音識別器,以及 RecognizeOnceAsync 呼叫語音轉文字 API。

  1. 使用 SpeechConfig 物件封裝連接 Foundry 資源所需的資訊。 具體來說,是它的 終點 (或 區域)和 金鑰。
  2. (選擇性) 使用 AudioConfig 定義要轉譯之音訊的輸入來源。 根據預設,這是預設的系統麥克風,但您也可以指定音訊檔案。
  3. 使用 SpeechConfig 和 AudioConfig 來建立 SpeechRecognizer 物件。 這個物件是 語音轉文字 API 的代理用戶端。
  4. 使用 SpeechRecognizer 物件的方法來呼叫基礎 API 函式。 例如, RecognizeOnceAsync() 方法利用 Azure 語音服務非同步轉錄單一口語。
  5. 處理回應。 在 RecognizeOnceAsync() 方法的案例中,結果是 SpeechRecognitionResult 物件,其中包含下列屬性:
    • 持續時間
    • OffsetInTicks
    • 屬性
    • 原因
    • 結果編號
    • 文字

如果操作成功,Reason 屬性具有列舉值 RecognizedSpeech,而 Text 屬性則包含轉錄。 其他可能的 Reason 值包括 NoMatch(表示音訊已成功解析但未辨識語音)或 Canceled,表示發生錯誤(此時你可以檢查 CancellationReason 屬性的 Properties 集合以判斷問題所在)。

範例 - 轉錄音訊檔案

以下 Python 範例使用 Foundry 工具中的 Azure 語音,將語音轉錄成音訊檔。

import azure.cognitiveservices.speech as speech_sdk

# Speech config encapsulates the connection to the resource
speech_config = speech_sdk.SpeechConfig(subscription="YOUR_FOUNDRY_KEY",
                                       endpoint="YOUR_FOUNDRY_ENDPOINT")

# Audio config determines the audio stream source (defaults to system mic)
file_path = "audio.wav"
audio_config = speech_sdk.audio.AudioConfig(filename=file_path)

# Use a speech recognizer to transcribe the audio
speech_recognizer = speech_sdk.SpeechRecognizer(speech_config=speech_config,
                                               audio_config=audio_config)

result = speech_recognizer.recognize_once_async().get()

# Did it succeed
if result.reason == speech_sdk.ResultReason.RecognizedSpeech:
    # Yes!
    print(f"Transcription:\n{result.text}")
else:
    # No. Try to determine why.
    print("Error transcribing message: {}".format(result.reason))