如何辨識語音

參考文件 | 套件 (NuGet) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

建立語音設定

若要使用語音 SDK 呼叫語音服務,您必須建立 SpeechConfig 實例。 此類別包含訂用帳戶的相關信息,例如密鑰和相關聯的位置/區域、端點、主機或授權令牌。

  1. 使用您的金鑰和位置/區域建立 SpeechConfig 實例。
  2. Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

class Program 
{
    async static Task Main(string[] args)
    {
        var speechConfig = SpeechConfig.FromSubscription("YourSpeechKey", "YourSpeechRegion");
    }
}

您可以透過其他幾種方式初始化 SpeechConfig

  • 使用端點,並傳入語音服務端點。 金鑰或授權令牌是選擇性的。
  • 使用主機,並傳入主機位址。 金鑰或授權令牌是選擇性的。
  • 搭配相關聯的區域/位置使用授權令牌。

注意

無論您執行語音辨識、語音合成、翻譯或意圖辨識,您一律都會建立設定。

從麥克風辨識語音

若要使用您的裝置麥克風辨識語音,請使用 FromDefaultMicrophoneInput() 方法建立 AudioConfig 實例。 然後傳遞 speechConfigaudioConfigSpeechRecognizer初始化物件。

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

class Program 
{
    async static Task FromMic(SpeechConfig speechConfig)
    {
        using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
        using var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

        Console.WriteLine("Speak into your microphone.");
        var result = await speechRecognizer.RecognizeOnceAsync();
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
    }

    async static Task Main(string[] args)
    {
        var speechConfig = SpeechConfig.FromSubscription("YourSpeechKey", "YourSpeechRegion");
        await FromMic(speechConfig);
    }
}

如果您想要使用 特定的 音訊輸入裝置,則必須在 中 AudioConfig指定裝置識別碼。 瞭解如何 取得音訊輸入裝置的裝置 標識碼。

從檔案辨識語音

如果您想要從音訊檔案辨識語音,而不是麥克風,您仍然需要建立 AudioConfig 實例。 但在此情況下,您不會呼叫 FromDefaultMicrophoneInput()。 您呼叫 FromWavFileInput() 並傳遞檔案路徑:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

class Program 
{
    async static Task FromFile(SpeechConfig speechConfig)
    {
        using var audioConfig = AudioConfig.FromWavFileInput("PathToFile.wav");
        using var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

        var result = await speechRecognizer.RecognizeOnceAsync();
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
    }

    async static Task Main(string[] args)
    {
        var speechConfig = SpeechConfig.FromSubscription("YourSpeechKey", "YourSpeechRegion");
        await FromFile(speechConfig);
    }
}

從記憶體內部數據流辨識語音

對於許多使用案例,音訊數據可能來自 Azure Blob 儲存體,或者它原本已經在記憶體中做為byte[]實例或類似的原始數據結構。 下列範例會使用 PushAudioInputStream 來辨識語音,這基本上是抽象記憶體數據流。 範例程式代碼會執行下列動作:

  • 使用 接受 byte[] 實體的 Write() 函式,將原始音訊資料 (PCM) 寫入至 PushAudioInputStream
  • 使用 FileReader 來讀取.wav檔案以供示範之用。 如果您已在 實體中 byte[] 擁有音訊數據,您可以直接跳到將內容寫入輸入數據流。
  • 默認格式為16位、16-KHz單脈衝碼調節(PCM)數據。 若要自訂格式,您可以使用靜態函式 AudioStreamFormat.GetWaveFormatPCM(sampleRate, (byte)bitRate, (byte)channels)將 物件傳遞AudioStreamFormatCreatePushStream()
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

class Program 
{
    async static Task FromStream(SpeechConfig speechConfig)
    {
        var reader = new BinaryReader(File.OpenRead("PathToFile.wav"));
        using var audioConfigStream = AudioInputStream.CreatePushStream();
        using var audioConfig = AudioConfig.FromStreamInput(audioConfigStream);
        using var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

        byte[] readBytes;
        do
        {
            readBytes = reader.ReadBytes(1024);
            audioConfigStream.Write(readBytes, readBytes.Length);
        } while (readBytes.Length > 0);

        var result = await speechRecognizer.RecognizeOnceAsync();
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
    }

    async static Task Main(string[] args)
    {
        var speechConfig = SpeechConfig.FromSubscription("YourSpeechKey", "YourSpeechRegion");
        await FromStream(speechConfig);
    }
}

使用推播數據流作為輸入會假設音訊數據是未經處理的 PCM,並略過任何標頭。 如果標頭尚未略過,API 仍可在某些情況下運作。 為了獲得最佳結果,請考慮實作邏輯來讀取標頭,以便byte[]從音訊數據開頭開始

處理錯誤

上述範例只會從 屬性取得辨識的 result.Text 文字。 若要處理錯誤和其他回應,您必須撰寫一些程式代碼來處理結果。 下列程式代碼會 result.Reason 評估 屬性和:

  • 列印辨識結果: ResultReason.RecognizedSpeech
  • 如果沒有辨識相符專案,它會通知使用者: ResultReason.NoMatch
  • 如果發生錯誤,它會列印錯誤訊息: ResultReason.Canceled
switch (result.Reason)
{
    case ResultReason.RecognizedSpeech:
        Console.WriteLine($"RECOGNIZED: Text={result.Text}");
        break;
    case ResultReason.NoMatch:
        Console.WriteLine($"NOMATCH: Speech could not be recognized.");
        break;
    case ResultReason.Canceled:
        var cancellation = CancellationDetails.FromResult(result);
        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

        if (cancellation.Reason == CancellationReason.Error)
        {
            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
            Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
            Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
        }
        break;
}

使用連續辨識

上述範例使用單次辨識,可辨識單一語句。 單一語句的結尾取決於在結尾接聽無聲,或直到處理最多 15 秒的音訊為止。

相反地,當您想要控制何時停止辨識時,您會使用連續辨識。 您必須訂閱 RecognizingRecognizedCanceled 事件,才能取得辨識結果。 若要停止辨識,您必須呼叫 StopContinuousRecognitionAsync。 以下是如何在音訊輸入檔上執行連續辨識的範例。

首先,定義輸入並初始化 SpeechRecognizer

using var audioConfig = AudioConfig.FromWavFileInput("YourAudioFile.wav");
using var speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

然後建立 TaskCompletionSource<int> 實體來管理語音辨識的狀態:

var stopRecognition = new TaskCompletionSource<int>();

接下來,訂閱傳送下列事件 SpeechRecognizer

  • Recognizing:包含中繼辨識結果的事件訊號。
  • Recognized:包含最終辨識結果的事件訊號,表示成功辨識嘗試。
  • SessionStopped:指出辨識會話結尾之事件的訊號(作業)。
  • Canceled:包含已取消辨識結果的事件訊號。 這些結果表示因直接取消要求而取消的辨識嘗試。 或者,它們表示傳輸或通訊協議失敗。
speechRecognizer.Recognizing += (s, e) =>
{
    Console.WriteLine($"RECOGNIZING: Text={e.Result.Text}");
};

speechRecognizer.Recognized += (s, e) =>
{
    if (e.Result.Reason == ResultReason.RecognizedSpeech)
    {
        Console.WriteLine($"RECOGNIZED: Text={e.Result.Text}");
    }
    else if (e.Result.Reason == ResultReason.NoMatch)
    {
        Console.WriteLine($"NOMATCH: Speech could not be recognized.");
    }
};

speechRecognizer.Canceled += (s, e) =>
{
    Console.WriteLine($"CANCELED: Reason={e.Reason}");

    if (e.Reason == CancellationReason.Error)
    {
        Console.WriteLine($"CANCELED: ErrorCode={e.ErrorCode}");
        Console.WriteLine($"CANCELED: ErrorDetails={e.ErrorDetails}");
        Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
    }

    stopRecognition.TrySetResult(0);
};

speechRecognizer.SessionStopped += (s, e) =>
{
    Console.WriteLine("\n    Session stopped event.");
    stopRecognition.TrySetResult(0);
};

設定好所有專案后,請呼叫 StartContinuousRecognitionAsync 以開始辨識:

await speechRecognizer.StartContinuousRecognitionAsync();

// Waits for completion. Use Task.WaitAny to keep the task rooted.
Task.WaitAny(new[] { stopRecognition.Task });

// Make the following call at some point to stop recognition:
// await speechRecognizer.StopContinuousRecognitionAsync();

變更來源語言

語音辨識的常見工作是指定輸入(或來源)語言。 下列範例示範如何將輸入語言變更為義大利文。 在您的程式代碼中,尋找您的 SpeechConfig 實例,並在其正下方新增這一行:

speechConfig.SpeechRecognitionLanguage = "it-IT";

屬性 SpeechRecognitionLanguage 需要語言地區設定格式字串。 如需詳細資訊,請參閱 支援的語音轉換文字地區設定清單。

語言識別

當您需要識別音訊來源中的語言,然後將它轉譯為文字時,您可以使用 語言識別 與語音轉換文字辨識。

如需完整的程式碼範例,請參閱 語言識別

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自定義端點。

var speechConfig = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");
speechConfig.EndpointId = "YourEndpointId";
var speechRecognizer = new SpeechRecognizer(speechConfig);

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

變更處理無聲的方式

如果使用者預期說話速度比平常快或慢,輸入音訊中非語音靜音的預設行為可能會導致您預期的結果。 無聲處理常見問題包括:

  • 快速語音將許多句子鏈結成單一辨識結果,而不是將句子分成個別結果。
  • 將單一句子的各個部分分隔成多個結果的緩慢語音。
  • 在等待語音開始時,單次辨識結束太快。

在用來建立 SpeechRecognizer的 實例上SpeechConfig設定兩個逾時屬性之一,即可解決這些問題:

  • 分割無聲逾時 會調整在詞組中允許多少非語音音訊,該片語目前在該片語被視為「完成」之前說出。
    • 較高的 值通常會讓結果更長,並允許在片語內從說話者暫停較長,但讓結果需要較長的時間才能到達。 當設定太高時,它們也可以將個別的片語結合成單一結果。
    • 較低的 值通常會縮短結果,並確保片語之間的提示和頻繁中斷,但也可能導致單一片語在設定太低時分成多個結果。
    • 此逾時可以設定為介於100到5000之間的整數值,以毫秒為單位,而一般預設值為500。
  • 初始無聲逾時會調整在辨識嘗試結束於「不相符」結果的片語之前,允許多少非語音音訊。
    • 較高的 值可讓說話者有更多時間回應並開始說話,但也可能會導致無話可說出時回應速度緩慢。
    • 較低的 值可確保提示「不相符」,以獲得更快的用戶體驗和更受控制的音訊處理,但在設定太低時,可能會將喇叭關閉太快。
    • 由於連續辨識會產生許多結果,因此此值會決定「不相符」結果到達的頻率,但不會影響辨識結果的內容。
    • 此逾時可以設定為任何非負整數值,以毫秒為單位,或設定為 0 以完全停用。 5000 是單次辨識的典型預設值,而 15000 是連續辨識的典型預設值。

修改這些逾時時有取捨時,只有在發生與無聲處理相關的問題時,才應該變更設定。 默認值會以最佳方式處理大部分口語音頻,而且只有不常見的案例應該會遇到問題。

範例: 說話的序號,例如 “ABC-123-4567” 的使用者可能會在字元群組之間暫停足夠長的時間,讓序號分成多個結果。 在此情況下,請嘗試較高的值,例如 2000 毫秒的分割無聲逾時:

speechConfig.SetProperty(PropertyId.Speech_SegmentationSilenceTimeoutMs, "2000");

範例: 錄製的演示者的語音速度可能夠快,而一個數據列中的數個句子會結合,而大型辨識結果只會每分鐘到達一次或兩次。 在此情況下,請將分割無聲逾時設定為較低的值,例如 300 毫秒:

speechConfig.SetProperty(PropertyId.Speech_SegmentationSilenceTimeoutMs, "300");

範例: 單次辨識會要求說話者尋找並讀取序號在找到數位時過快結束。 在此情況下,請嘗試較長的初始無聲逾時,例如 10,000 毫秒:

speechConfig.SetProperty(PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, "10000");

參考文件 | 套件 (NuGet) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

建立語音設定

若要使用語音 SDK 呼叫語音服務,您必須建立 SpeechConfig 實例。 此類別包含訂用帳戶的相關信息,例如密鑰和相關聯的位置/區域、端點、主機或授權令牌。

  1. 使用您的金鑰和區域建立 SpeechConfig 實例。
  2. Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源
using namespace std;
using namespace Microsoft::CognitiveServices::Speech;

auto speechConfig = SpeechConfig::FromSubscription("YourSpeechKey", "YourSpeechRegion");

您可以透過其他幾種方式初始化 SpeechConfig

  • 使用端點,並傳入語音服務端點。 金鑰或授權令牌是選擇性的。
  • 使用主機,並傳入主機位址。 金鑰或授權令牌是選擇性的。
  • 搭配相關聯的區域/位置使用授權令牌。

注意

無論您執行語音辨識、語音合成、翻譯或意圖辨識,您一律都會建立設定。

從麥克風辨識語音

若要使用裝置麥克風辨識語音,請使用FromDefaultMicrophoneInput()成員函式建立AudioConfig實例。 然後傳遞 audioConfigconfigSpeechRecognizer初始化物件。

using namespace Microsoft::CognitiveServices::Speech::Audio;

auto audioConfig = AudioConfig::FromDefaultMicrophoneInput();
auto speechRecognizer = SpeechRecognizer::FromConfig(config, audioConfig);

cout << "Speak into your microphone." << std::endl;
auto result = speechRecognizer->RecognizeOnceAsync().get();
cout << "RECOGNIZED: Text=" << result->Text << std::endl;

如果您想要使用 特定的 音訊輸入裝置,則必須在 中 AudioConfig指定裝置識別碼。 如需如何取得音訊輸入裝置裝置標識碼的詳細資訊,請參閱 使用語音 SDK 選取音訊輸入設備

從檔案辨識語音

如果您想要從音訊檔案辨識語音,而不是使用麥克風,您仍然需要建立 AudioConfig 實例。 但在此情況下,您不會呼叫 FromDefaultMicrophoneInput()。 您呼叫 FromWavFileInput() 並傳遞檔案路徑:

using namespace Microsoft::CognitiveServices::Speech::Audio;

auto audioConfig = AudioConfig::FromWavFileInput("YourAudioFile.wav");
auto speechRecognizer = SpeechRecognizer::FromConfig(config, audioConfig);

auto result = speechRecognizer->RecognizeOnceAsync().get();
cout << "RECOGNIZED: Text=" << result->Text << std::endl;

使用辨識器類別辨識語音

適用於 C++ 的語音 SDK 辨識器類別會公開一些可用於語音辨識的方法。

單次辨識

單次辨識會以異步方式辨識單一語句。 單一語句的結尾取決於在結尾接聽無聲,或直到處理最多 15 秒的音訊為止。 以下是透過 RecognizeOnceAsync的異步單次辨識範例:

auto result = speechRecognizer->RecognizeOnceAsync().get();

您需要撰寫一些程式代碼來處理結果。 此範例會 result->Reason 評估 和:

  • 列印辨識結果: ResultReason::RecognizedSpeech
  • 如果沒有辨識相符專案,它會通知使用者: ResultReason::NoMatch
  • 如果發生錯誤,它會列印錯誤訊息: ResultReason::Canceled
switch (result->Reason)
{
    case ResultReason::RecognizedSpeech:
        cout << "We recognized: " << result->Text << std::endl;
        break;
    case ResultReason::NoMatch:
        cout << "NOMATCH: Speech could not be recognized." << std::endl;
        break;
    case ResultReason::Canceled:
        {
            auto cancellation = CancellationDetails::FromResult(result);
            cout << "CANCELED: Reason=" << (int)cancellation->Reason << std::endl;
    
            if (cancellation->Reason == CancellationReason::Error) {
                cout << "CANCELED: ErrorCode= " << (int)cancellation->ErrorCode << std::endl;
                cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails << std::endl;
                cout << "CANCELED: Did you set the speech resource key and region values?" << std::endl;
            }
        }
        break;
    default:
        break;
}

連續辨識

連續辨識比單次辨識多一點。 您必須訂閱 RecognizingRecognizedCanceled 事件,才能取得辨識結果。 若要停止辨識,您必須呼叫 StopContinuousRecognitionAsync。 以下是如何在音訊輸入檔上執行連續辨識的範例。

首先,定義輸入並初始化 SpeechRecognizer

auto audioConfig = AudioConfig::FromWavFileInput("YourAudioFile.wav");
auto speechRecognizer = SpeechRecognizer::FromConfig(config, audioConfig);

接下來,建立變數來管理語音辨識的狀態。 宣告 promise<void> ,因為在辨識開始時,您可以放心地假設它尚未完成:

promise<void> recognitionEnd;

接下來,訂閱傳送下列事件 SpeechRecognizer

  • Recognizing:包含中繼辨識結果的事件訊號。
  • Recognized:包含最終辨識結果的事件訊號,表示成功辨識嘗試。
  • SessionStopped:指出辨識會話結尾之事件的訊號(作業)。
  • Canceled:包含已取消辨識結果的事件訊號。 這些結果表示因直接的取消要求而取消的辨識嘗試。 或者,它們表示傳輸或通訊協議失敗。
speechRecognizer->Recognizing.Connect([](const SpeechRecognitionEventArgs& e)
    {
        cout << "Recognizing:" << e.Result->Text << std::endl;
    });

speechRecognizer->Recognized.Connect([](const SpeechRecognitionEventArgs& e)
    {
        if (e.Result->Reason == ResultReason::RecognizedSpeech)
        {
            cout << "RECOGNIZED: Text=" << e.Result->Text 
                 << " (text could not be translated)" << std::endl;
        }
        else if (e.Result->Reason == ResultReason::NoMatch)
        {
            cout << "NOMATCH: Speech could not be recognized." << std::endl;
        }
    });

speechRecognizer->Canceled.Connect([&recognitionEnd](const SpeechRecognitionCanceledEventArgs& e)
    {
        cout << "CANCELED: Reason=" << (int)e.Reason << std::endl;
        if (e.Reason == CancellationReason::Error)
        {
            cout << "CANCELED: ErrorCode=" << (int)e.ErrorCode << "\n"
                 << "CANCELED: ErrorDetails=" << e.ErrorDetails << "\n"
                 << "CANCELED: Did you set the speech resource key and region values?" << std::endl;

            recognitionEnd.set_value(); // Notify to stop recognition.
        }
    });

speechRecognizer->SessionStopped.Connect([&recognitionEnd](const SessionEventArgs& e)
    {
        cout << "Session stopped.";
        recognitionEnd.set_value(); // Notify to stop recognition.
    });

設定好所有專案后,請呼叫 StopContinuousRecognitionAsync 以開始辨識:

// Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
speechRecognizer->StartContinuousRecognitionAsync().get();

// Waits for recognition end.
recognitionEnd.get_future().get();

// Stops recognition.
speechRecognizer->StopContinuousRecognitionAsync().get();

變更來源語言

語音辨識的常見工作是指定輸入(或來源)語言。 下列範例示範如何將輸入語言變更為德文。 在您的程式代碼中,尋找您的 SpeechConfig 實例,並在其正下方新增這一行:

speechConfig->SetSpeechRecognitionLanguage("de-DE");

SetSpeechRecognitionLanguage 是接受字串做為自變數的參數。 如需詳細資訊,請參閱 支援的語音轉換文字地區設定清單。

語言識別

當您需要識別音訊來源中的語言,然後將它轉譯為文字時,您可以使用 語言識別 與語音轉換文字辨識。

如需完整的程式碼範例,請參閱 語言識別

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自定義端點。

auto speechConfig = SpeechConfig::FromSubscription("YourSubscriptionKey", "YourServiceRegion");
speechConfig->SetEndpointId("YourEndpointId");
auto speechRecognizer = SpeechRecognizer::FromConfig(speechConfig);

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | 套件 (Go) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

從麥克風辨識語音轉換文字

使用下列程式代碼範例,從預設裝置麥克風執行語音辨識。 分別將變數 subscriptionregion 取代為您的語音密鑰和位置/區域。 在 Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源。 執行文稿會在預設麥克風和輸出文字上啟動辨識工作階段:

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
	"github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)

func sessionStartedHandler(event speech.SessionEventArgs) {
	defer event.Close()
	fmt.Println("Session Started (ID=", event.SessionID, ")")
}

func sessionStoppedHandler(event speech.SessionEventArgs) {
	defer event.Close()
	fmt.Println("Session Stopped (ID=", event.SessionID, ")")
}

func recognizingHandler(event speech.SpeechRecognitionEventArgs) {
	defer event.Close()
	fmt.Println("Recognizing:", event.Result.Text)
}

func recognizedHandler(event speech.SpeechRecognitionEventArgs) {
	defer event.Close()
	fmt.Println("Recognized:", event.Result.Text)
}

func cancelledHandler(event speech.SpeechRecognitionCanceledEventArgs) {
	defer event.Close()
	fmt.Println("Received a cancellation: ", event.ErrorDetails)
	fmt.Println("Did you set the speech resource key and region values?")
}

func main() {
    subscription :=  "YourSpeechKey"
    region := "YourSpeechRegion"

	audioConfig, err := audio.NewAudioConfigFromDefaultMicrophoneInput()
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer audioConfig.Close()
	config, err := speech.NewSpeechConfigFromSubscription(subscription, region)
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer config.Close()
	speechRecognizer, err := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer speechRecognizer.Close()
	speechRecognizer.SessionStarted(sessionStartedHandler)
	speechRecognizer.SessionStopped(sessionStoppedHandler)
	speechRecognizer.Recognizing(recognizingHandler)
	speechRecognizer.Recognized(recognizedHandler)
	speechRecognizer.Canceled(cancelledHandler)
	speechRecognizer.StartContinuousRecognitionAsync()
	defer speechRecognizer.StopContinuousRecognitionAsync()
	bufio.NewReader(os.Stdin).ReadBytes('\n')
}

執行下列命令來建立 go.mod 檔案,以連結至 GitHub 上裝載的元件:

go mod init quickstart
go get github.com/Microsoft/cognitive-services-speech-sdk-go

現在建置並執行程式代碼:

go build
go run quickstart

如需詳細資訊,請參閱 類別的參考內容SpeechConfig類別SpeechRecognizer參考內容。

辨識來自音訊檔案的語音轉換文字

使用下列範例從音訊檔案執行語音辨識。 分別將變數 subscriptionregion 取代為您的語音密鑰和位置/區域。 在 Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源。 此外,請將變數file取代為.wav檔案的路徑。 當您執行文稿時,它會辨識來自檔案的語音,並輸出文字結果:

package main

import (
	"fmt"
	"time"

	"github.com/Microsoft/cognitive-services-speech-sdk-go/audio"
	"github.com/Microsoft/cognitive-services-speech-sdk-go/speech"
)

func main() {
    subscription :=  "YourSpeechKey"
    region := "YourSpeechRegion"
    file := "path/to/file.wav"

	audioConfig, err := audio.NewAudioConfigFromWavFileInput(file)
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer audioConfig.Close()
	config, err := speech.NewSpeechConfigFromSubscription(subscription, region)
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer config.Close()
	speechRecognizer, err := speech.NewSpeechRecognizerFromConfig(config, audioConfig)
	if err != nil {
		fmt.Println("Got an error: ", err)
		return
	}
	defer speechRecognizer.Close()
	speechRecognizer.SessionStarted(func(event speech.SessionEventArgs) {
		defer event.Close()
		fmt.Println("Session Started (ID=", event.SessionID, ")")
	})
	speechRecognizer.SessionStopped(func(event speech.SessionEventArgs) {
		defer event.Close()
		fmt.Println("Session Stopped (ID=", event.SessionID, ")")
	})

	task := speechRecognizer.RecognizeOnceAsync()
	var outcome speech.SpeechRecognitionOutcome
	select {
	case outcome = <-task:
	case <-time.After(5 * time.Second):
		fmt.Println("Timed out")
		return
	}
	defer outcome.Close()
	if outcome.Error != nil {
		fmt.Println("Got an error: ", outcome.Error)
	}
	fmt.Println("Got a recognition!")
	fmt.Println(outcome.Result.Text)
}

執行下列命令來建立 go.mod 檔案,以連結至 GitHub 上裝載的元件:

go mod init quickstart
go get github.com/Microsoft/cognitive-services-speech-sdk-go

現在建置並執行程式代碼:

go build
go run quickstart

如需詳細資訊,請參閱 類別的參考內容SpeechConfig類別SpeechRecognizer參考內容。

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

建立語音設定

若要使用語音 SDK 呼叫語音服務,您需要建立 SpeechConfig 實例。 此類別包含訂用帳戶的相關信息,例如密鑰和相關聯的位置/區域、端點、主機或授權令牌。

  1. 使用您的金鑰和位置/區域建立 SpeechConfig 實例。
  2. Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Program {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SpeechConfig speechConfig = SpeechConfig.fromSubscription("<paste-your-subscription-key>", "<paste-your-region>");
    }
}

您可以透過其他幾種方式初始化 SpeechConfig

  • 使用端點,並傳入語音服務端點。 金鑰或授權令牌是選擇性的。
  • 使用主機,並傳入主機位址。 金鑰或授權令牌是選擇性的。
  • 搭配相關聯的區域/位置使用授權令牌。

注意

無論您執行語音辨識、語音合成、翻譯或意圖辨識,您一律都會建立設定。

從麥克風辨識語音

若要使用您的裝置麥克風辨識語音,請使用 fromDefaultMicrophoneInput() 方法建立 AudioConfig 實例。 然後傳遞 audioConfigconfigSpeechRecognizer初始化物件。

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Program {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SpeechConfig speechConfig = SpeechConfig.fromSubscription("<paste-your-subscription-key>", "<paste-your-region>");
        fromMic(speechConfig);
    }

    public static void fromMic(SpeechConfig speechConfig) throws InterruptedException, ExecutionException {
        AudioConfig audioConfig = AudioConfig.fromDefaultMicrophoneInput();
        SpeechRecognizer speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

        System.out.println("Speak into your microphone.");
        Future<SpeechRecognitionResult> task = speechRecognizer.recognizeOnceAsync();
        SpeechRecognitionResult result = task.get();
        System.out.println("RECOGNIZED: Text=" + result.getText());
    }
}

如果您想要使用 特定的 音訊輸入裝置,則必須在 中 AudioConfig指定裝置識別碼。 如需如何取得音訊輸入裝置裝置標識碼的詳細資訊,請參閱 使用語音 SDK 選取音訊輸入裝置。

從檔案辨識語音

如果您想要從音訊檔案辨識語音,而不是使用麥克風,您仍然需要建立 AudioConfig 實例。 但在此情況下,您不會呼叫 FromDefaultMicrophoneInput()。 您呼叫 fromWavFileInput() 並傳遞檔案路徑:

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Program {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        SpeechConfig speechConfig = SpeechConfig.fromSubscription("<paste-your-subscription-key>", "<paste-your-region>");
        fromFile(speechConfig);
    }

    public static void fromFile(SpeechConfig speechConfig) throws InterruptedException, ExecutionException {
        AudioConfig audioConfig = AudioConfig.fromWavFileInput("YourAudioFile.wav");
        SpeechRecognizer speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);
        
        Future<SpeechRecognitionResult> task = speechRecognizer.recognizeOnceAsync();
        SpeechRecognitionResult result = task.get();
        System.out.println("RECOGNIZED: Text=" + result.getText());
    }
}

處理錯誤

上述範例只會使用 result.getText()取得辨識的文字。 若要處理錯誤和其他回應,您必須撰寫一些程式代碼來處理結果。 下列範例會 result.getReason() 評估 和:

  • 列印辨識結果: ResultReason.RecognizedSpeech
  • 如果沒有辨識相符專案,它會通知使用者: ResultReason.NoMatch
  • 如果發生錯誤,它會列印錯誤訊息: ResultReason.Canceled
switch (result.getReason()) {
    case ResultReason.RecognizedSpeech:
        System.out.println("We recognized: " + result.getText());
        exitCode = 0;
        break;
    case ResultReason.NoMatch:
        System.out.println("NOMATCH: Speech could not be recognized.");
        break;
    case ResultReason.Canceled: {
            CancellationDetails cancellation = CancellationDetails.fromResult(result);
            System.out.println("CANCELED: Reason=" + cancellation.getReason());

            if (cancellation.getReason() == CancellationReason.Error) {
                System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
                System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
                System.out.println("CANCELED: Did you set the speech resource key and region values?");
            }
        }
        break;
}

使用連續辨識

上述範例使用單次辨識,可辨識單一語句。 單一語句的結尾取決於在結尾接聽無聲,或直到處理最多 15 秒的音訊為止。

相反地,當您想要控制何時停止辨識時,您會使用連續辨識。 您必須訂閱 recognizingrecognizedcanceled 事件,才能取得辨識結果。 若要停止辨識,您必須呼叫 stopContinuousRecognitionAsync。 以下是如何在音訊輸入檔上執行連續辨識的範例。

首先,定義輸入並初始化 SpeechRecognizer

AudioConfig audioConfig = AudioConfig.fromWavFileInput("YourAudioFile.wav");
SpeechRecognizer speechRecognizer = new SpeechRecognizer(config, audioConfig);

接下來,建立變數來管理語音辨識的狀態。 在 Semaphore 類別範圍宣告實例:

private static Semaphore stopTranslationWithFileSemaphore;

接下來,訂閱傳送下列事件 SpeechRecognizer

  • recognizing:包含中繼辨識結果的事件訊號。
  • recognized:包含最終辨識結果的事件訊號,表示成功辨識嘗試。
  • sessionStopped:指出辨識會話結尾之事件的訊號(作業)。
  • canceled:包含已取消辨識結果的事件訊號。 這些結果表示因直接取消要求而取消的辨識嘗試。 或者,它們表示傳輸或通訊協議失敗。
// First initialize the semaphore.
stopTranslationWithFileSemaphore = new Semaphore(0);

speechRecognizer.recognizing.addEventListener((s, e) -> {
    System.out.println("RECOGNIZING: Text=" + e.getResult().getText());
});

speechRecognizer.recognized.addEventListener((s, e) -> {
    if (e.getResult().getReason() == ResultReason.RecognizedSpeech) {
        System.out.println("RECOGNIZED: Text=" + e.getResult().getText());
    }
    else if (e.getResult().getReason() == ResultReason.NoMatch) {
        System.out.println("NOMATCH: Speech could not be recognized.");
    }
});

speechRecognizer.canceled.addEventListener((s, e) -> {
    System.out.println("CANCELED: Reason=" + e.getReason());

    if (e.getReason() == CancellationReason.Error) {
        System.out.println("CANCELED: ErrorCode=" + e.getErrorCode());
        System.out.println("CANCELED: ErrorDetails=" + e.getErrorDetails());
        System.out.println("CANCELED: Did you set the speech resource key and region values?");
    }

    stopTranslationWithFileSemaphore.release();
});

speechRecognizer.sessionStopped.addEventListener((s, e) -> {
    System.out.println("\n    Session stopped event.");
    stopTranslationWithFileSemaphore.release();
});

設定好所有專案后,請呼叫 startContinuousRecognitionAsync 以開始辨識:

// Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
speechRecognizer.startContinuousRecognitionAsync().get();

// Waits for completion.
stopTranslationWithFileSemaphore.acquire();

// Stops recognition.
speechRecognizer.stopContinuousRecognitionAsync().get();

變更來源語言

語音辨識的常見工作是指定輸入(或來源)語言。 下列範例示範如何將輸入語言變更為法文。 在您的程式代碼中,尋找您的 SpeechConfig 實例,並在其正下方新增這一行:

config.setSpeechRecognitionLanguage("fr-FR");

setSpeechRecognitionLanguage 是接受字串做為自變數的參數。 請參閱支援的語音轉換文字地區設定清單

語言識別

當您需要識別音訊來源中的語言,然後將它轉譯為文字時,您可以使用 語言識別 與語音轉換文字辨識。

如需完整的程式碼範例,請參閱 語言識別

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自訂端點:

SpeechConfig speechConfig = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");
speechConfig.setEndpointId("YourEndpointId");
SpeechRecognizer speechRecognizer = new SpeechRecognizer(speechConfig);

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | 套件 (npm) | GitHub 上的其他範例 | 程式庫原始程式碼

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

建立語音設定

若要使用語音 SDK 呼叫語音服務,您必須建立 SpeechConfig 實例。 此類別包含訂用帳戶的相關信息,例如密鑰和相關聯的位置/區域、端點、主機或授權令牌。

  1. 使用您的金鑰和位置/區域建立 SpeechConfig 實例。
  2. Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源
const speechConfig = sdk.SpeechConfig.fromSubscription("YourSpeechKey", "YourSpeechRegion");

您可以透過其他幾種方式初始化 SpeechConfig

  • 使用端點,並傳入語音服務端點。 金鑰或授權令牌是選擇性的。
  • 使用主機,並傳入主機位址。 金鑰或授權令牌是選擇性的。
  • 搭配相關聯的區域/位置使用授權令牌。

注意

無論您執行語音辨識、語音合成、翻譯或意圖辨識,您一律都會建立設定。

從麥克風辨識語音

Node.js不支援從麥克風辨識語音。 它只支援在瀏覽器型 JavaScript 環境中。 如需詳細資訊,請參閱 React 範例,以及 GitHub 上的從麥克風進行語音轉換文字實作。 React 範例會顯示驗證令牌交換和管理的設計模式。 該範例也會顯示要進行語音轉換文字時從麥克風或檔案的音訊擷取。

注意

如果您想要使用 特定的 音訊輸入裝置,則必須在物件中 AudioConfig 指定裝置標識碼。 如需詳細資訊,請參閱 使用語音 SDK 選取音訊輸入設備。

從檔案辨識語音

若要辨識音訊檔案中的語音,請使用 fromWavFileInput() 接受物件的 方法來Buffer建立 AudioConfig 實例。 然後傳遞 audioConfigspeechConfig來初始化SpeechRecognizer

const fs = require('fs');
const sdk = require("microsoft-cognitiveservices-speech-sdk");
const speechConfig = sdk.SpeechConfig.fromSubscription("YourSpeechKey", "YourSpeechRegion");

function fromFile() {
    let audioConfig = sdk.AudioConfig.fromWavFileInput(fs.readFileSync("YourAudioFile.wav"));
    let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);

    speechRecognizer.recognizeOnceAsync(result => {
        console.log(`RECOGNIZED: Text=${result.text}`);
        speechRecognizer.close();
    });
}
fromFile();

從記憶體內部數據流辨識語音

對於許多使用案例,音訊數據可能來自 Azure Blob 儲存體。 或者它已經在記憶體中作為 ArrayBuffer 或類似的原始數據結構。 下列程式碼範例:

  • 使用 createPushStream()建立推送數據流。
  • 使用 fs.createReadStream 來讀取.wav檔案以供示範之用。 如果您已經在 中 ArrayBuffer擁有音訊數據,您可以直接跳到將內容寫入輸入數據流。
  • 使用推送數據流建立音訊組態。
const fs = require('fs');
const sdk = require("microsoft-cognitiveservices-speech-sdk");
const speechConfig = sdk.SpeechConfig.fromSubscription("YourSpeechKey", "YourSpeechRegion");

function fromStream() {
    let pushStream = sdk.AudioInputStream.createPushStream();

    fs.createReadStream("YourAudioFile.wav").on('data', function(arrayBuffer) {
        pushStream.write(arrayBuffer.slice());
    }).on('end', function() {
        pushStream.close();
    });
 
    let audioConfig = sdk.AudioConfig.fromStreamInput(pushStream);
    let speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
    speechRecognizer.recognizeOnceAsync(result => {
        console.log(`RECOGNIZED: Text=${result.text}`);
        speechRecognizer.close();
    });
}
fromStream();

使用推送串流做為輸入,假設音訊數據是略過任何標頭的原始脈衝碼調節 (PCM) 數據。 如果未略過標頭,則 API 在某些情況下仍可運作。 為了獲得最佳結果,請考慮實作邏輯來讀取標頭,以便fs從音訊數據開頭開始

處理錯誤

上述範例只會從 屬性取得辨識的 result.text 文字。 若要處理錯誤和其他回應,您必須撰寫一些程式代碼來處理結果。 下列程式代碼會 result.reason 評估 屬性和:

  • 列印辨識結果: ResultReason.RecognizedSpeech
  • 如果沒有辨識相符專案,它會通知使用者: ResultReason.NoMatch
  • 如果發生錯誤,它會列印錯誤訊息: ResultReason.Canceled
switch (result.reason) {
    case sdk.ResultReason.RecognizedSpeech:
        console.log(`RECOGNIZED: Text=${result.text}`);
        break;
    case sdk.ResultReason.NoMatch:
        console.log("NOMATCH: Speech could not be recognized.");
        break;
    case sdk.ResultReason.Canceled:
        const cancellation = sdk.CancellationDetails.fromResult(result);
        console.log(`CANCELED: Reason=${cancellation.reason}`);

        if (cancellation.reason == sdk.CancellationReason.Error) {
            console.log(`CANCELED: ErrorCode=${cancellation.ErrorCode}`);
            console.log(`CANCELED: ErrorDetails=${cancellation.errorDetails}`);
            console.log("CANCELED: Did you set the speech resource key and region values?");
        }
        break;
    }

使用連續辨識

上述範例使用單次辨識,可辨識單一語句。 單一語句的結尾取決於在結尾接聽無聲,或直到處理最多 15 秒的音訊為止。

相反地,當您想要控制何時停止辨識時,可以使用連續辨識。 您必須訂閱 RecognizingRecognizedCanceled 事件,才能取得辨識結果。 若要停止辨識,您必須呼叫 stopContinuousRecognitionAsync。 以下是如何在音訊輸入檔上執行連續辨識的範例。

首先,定義輸入並初始化 SpeechRecognizer

const speechRecognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);

接下來,訂閱從 SpeechRecognizer傳送的事件:

  • recognizing:包含中繼辨識結果的事件訊號。
  • recognized:包含最終辨識結果的事件訊號,表示成功辨識嘗試。
  • sessionStopped:指出辨識會話結尾之事件的訊號(作業)。
  • canceled:包含已取消辨識結果的事件訊號。 這些結果表示因直接取消要求而取消的辨識嘗試。 或者,它們表示傳輸或通訊協議失敗。
speechRecognizer.recognizing = (s, e) => {
    console.log(`RECOGNIZING: Text=${e.result.text}`);
};

speechRecognizer.recognized = (s, e) => {
    if (e.result.reason == sdk.ResultReason.RecognizedSpeech) {
        console.log(`RECOGNIZED: Text=${e.result.text}`);
    }
    else if (e.result.reason == sdk.ResultReason.NoMatch) {
        console.log("NOMATCH: Speech could not be recognized.");
    }
};

speechRecognizer.canceled = (s, e) => {
    console.log(`CANCELED: Reason=${e.reason}`);

    if (e.reason == sdk.CancellationReason.Error) {
        console.log(`"CANCELED: ErrorCode=${e.errorCode}`);
        console.log(`"CANCELED: ErrorDetails=${e.errorDetails}`);
        console.log("CANCELED: Did you set the speech resource key and region values?");
    }

    speechRecognizer.stopContinuousRecognitionAsync();
};

speechRecognizer.sessionStopped = (s, e) => {
    console.log("\n    Session stopped event.");
    speechRecognizer.stopContinuousRecognitionAsync();
};

設定好所有專案后,請呼叫 startContinuousRecognitionAsync 以開始辨識:

speechRecognizer.startContinuousRecognitionAsync();

// Make the following call at some point to stop recognition:
// speechRecognizer.stopContinuousRecognitionAsync();

變更來源語言

語音辨識的常見工作是指定輸入(或來源)語言。 下列範例示範如何將輸入語言變更為義大利文。 在您的程式代碼中,尋找您的 SpeechConfig 實例,並在其正下方新增這一行:

speechConfig.speechRecognitionLanguage = "it-IT";

屬性 speechRecognitionLanguage 需要語言地區設定格式字串。 如需詳細資訊,請參閱 支援的語音轉換文字地區設定清單。

語言識別

當您需要識別音訊來源中的語言,然後將它轉譯為文字時,您可以使用 語言識別 與語音轉換文字辨識。

如需完整的程式碼範例,請參閱 語言識別

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自定義端點。

var speechConfig = SpeechSDK.SpeechConfig.fromSubscription("YourSubscriptionKey", "YourServiceRegion");
speechConfig.endpointId = "YourEndpointId";
var speechRecognizer = new SpeechSDK.SpeechRecognizer(speechConfig);

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | 套件 (下載) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

安裝語音 SDK 和範例

Azure-Samples/cognitive-services-speech-sdk 存放庫包含以適用於 iOS 和 Mac 的 Objective-C 撰寫的範例。 選取連結以檢視每個範例的安裝指示:

如需詳細資訊,請參閱適用於 Objective-C 的 語音 SDK 參考

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自訂端點:

SPXSpeechConfiguration *speechConfig = [[SPXSpeechConfiguration alloc] initWithSubscription:"YourSubscriptionKey" region:"YourServiceRegion"];
speechConfig.endpointId = "YourEndpointId";
SPXSpeechRecognizer* speechRecognizer = [[SPXSpeechRecognizer alloc] init:speechConfig];

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | 套件 (下載) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

安裝語音 SDK 和範例

Azure-Samples/cognitive-services-speech-sdk 存放庫包含以 Swift for iOS 和 Mac 撰寫的範例。 選取連結以檢視每個範例的安裝指示:

如需詳細資訊,請參閱 適用於 Swift 的語音 SDK 參考

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自訂端點:

let speechConfig = SPXSpeechConfiguration(subscription: "YourSubscriptionKey", region: "YourServiceRegion");
speechConfig.endpointId = "YourEndpointId";
let speechRecognizer = SPXSpeechRecognizer(speechConfiguration: speechConfig);

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

參考文件 | 套件 (PyPi) | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

建立語音設定

若要使用語音 SDK 呼叫語音服務,您必須建立 SpeechConfig 實例。 此類別包含訂用帳戶的相關信息,例如您的語音密鑰和相關聯的位置/區域、端點、主機或授權令牌。

  1. 使用語音金鑰和位置/區域建立 SpeechConfig 實例。
  2. Azure 入口網站上建立語音資源。 如需詳細資訊,請參閱建立多服務資源
speech_config = speechsdk.SpeechConfig(subscription="YourSpeechKey", region="YourSpeechRegion")

您可以透過其他幾種方式初始化 SpeechConfig

  • 使用端點,並傳入語音服務端點。 語音金鑰或授權令牌是選擇性的。
  • 使用主機,並傳入主機位址。 語音金鑰或授權令牌是選擇性的。
  • 搭配相關聯的區域/位置使用授權令牌。

注意

無論您執行語音辨識、語音合成、翻譯或意圖辨識,您一律都會建立設定。

從麥克風辨識語音

若要使用裝置麥克風辨識語音,請建立 SpeechRecognizer 實例而不傳遞 AudioConfig,然後傳遞 speech_config

import azure.cognitiveservices.speech as speechsdk

def from_mic():
    speech_config = speechsdk.SpeechConfig(subscription="YourSpeechKey", region="YourSpeechRegion")
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)

    print("Speak into your microphone.")
    result = speech_recognizer.recognize_once_async().get()
    print(result.text)

from_mic()

如果您想要使用 特定的 音訊輸入裝置,您必須在 中 AudioConfig指定裝置識別碼,並將它傳遞至 SpeechRecognizer 建構函式的參數 audio_config 。 如需如何取得音訊輸入裝置裝置標識碼的詳細資訊,請參閱 使用語音 SDK 選取音訊輸入設備

從檔案辨識語音

如果您想要從音訊檔案辨識語音,而不是使用麥克風,請建立 AudioConfig 實例並使用 filename 參數:

import azure.cognitiveservices.speech as speechsdk

def from_file():
    speech_config = speechsdk.SpeechConfig(subscription="YourSpeechKey", region="YourSpeechRegion")
    audio_config = speechsdk.AudioConfig(filename="your_file_name.wav")
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

    result = speech_recognizer.recognize_once_async().get()
    print(result.text)

from_file()

處理錯誤

上述範例只會從 屬性取得辨識的 result.text 文字。 若要處理錯誤和其他回應,您必須撰寫一些程式代碼來處理結果。 下列程式代碼會 result.reason 評估 屬性和:

  • 列印辨識結果: speechsdk.ResultReason.RecognizedSpeech
  • 如果沒有辨識相符專案,它會通知使用者: speechsdk.ResultReason.NoMatch
  • 如果發生錯誤,它會列印錯誤訊息: speechsdk.ResultReason.Canceled
if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print("Recognized: {}".format(result.text))
elif result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized: {}".format(result.no_match_details))
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print("Speech Recognition canceled: {}".format(cancellation_details.reason))
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("Error details: {}".format(cancellation_details.error_details))
        print("Did you set the speech resource key and region values?")

使用連續辨識

上述範例使用單次辨識,可辨識單一語句。 單一語句的結尾取決於在結尾接聽無聲,或直到處理最多 15 秒的音訊為止。

相反地,當您想要控制何時停止辨識時,您會使用連續辨識。 您必須連線到 EventSignal 以取得辨識結果。 若要停止辨識,您必須呼叫 stop_continuous_recognition()stop_continuous_recognition() 。 以下是如何在音訊輸入檔上執行連續辨識的範例。

首先,定義輸入並初始化 SpeechRecognizer

audio_config = speechsdk.audio.AudioConfig(filename=weatherfilename)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

接下來,建立變數來管理語音辨識的狀態。 將 變數設定為 False ,因為在辨識開始時,您可以放心地假設它尚未完成:

done = False

現在,建立回呼,以在收到時 evt 停止連續辨識。 請記住以下幾點:

def stop_cb(evt):
    print('CLOSING on {}'.format(evt))
    speech_recognizer.stop_continuous_recognition()
    nonlocal done
    done = True

下列程式代碼範例示範如何將回呼聯機到從 SpeechRecognizer傳送的事件。 事件如下:

  • recognizing:包含中繼辨識結果的事件訊號。
  • recognized:包含最終辨識結果的事件訊號,表示成功辨識嘗試。
  • session_started:指出辨識會話 (作業) 開始的事件訊號。
  • session_stopped:指出辨識會話結尾之事件的訊號(作業)。
  • canceled:包含已取消辨識結果的事件訊號。 這些結果表示因直接取消要求而取消的辨識嘗試。 或者,它們表示傳輸或通訊協議失敗。
speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED: {}'.format(evt)))
speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))

speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)

設定好所有專案后,您可以呼叫 start_continuous_recognition()

speech_recognizer.start_continuous_recognition()
while not done:
    time.sleep(.5)

變更來源語言

語音辨識的常見工作是指定輸入(或來源)語言。 下列範例示範如何將輸入語言變更為德文。 在您的程式代碼中,尋找您的 SpeechConfig 實例,並在其正下方新增這一行:

speech_config.speech_recognition_language="de-DE"

speech_recognition_language 是接受字串做為自變數的參數。 如需詳細資訊,請參閱 支援的語音轉換文字地區設定清單。

語言識別

當您需要識別音訊來源中的語言,然後轉錄為文字時,您可以將語言辨識與語音轉換文字辨識搭配使用。

如需完整的程式碼範例,請參閱 語言識別

使用自訂端點

透過 自訂語音,您可以上傳自己的數據、測試及定型自定義模型、比較模型之間的精確度,以及將模型部署至自定義端點。 下列範例示範如何設定自定義端點。

speech_config = speechsdk.SpeechConfig(subscription="YourSubscriptionKey", region="YourServiceRegion")
speech_config.endpoint_id = "YourEndpointId"
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config)

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

語音轉換文字 REST API 參考 | 適用於簡短音訊的語音轉換文字 REST API 參考 | GitHub 上的其他範例

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

語音轉換文字

在命令提示字元中,執行下列命令。 將下列值插入命令中:

  • 語音服務的訂用帳戶密鑰。
  • 您的語音服務區域。
  • 輸入音訊檔案的路徑。 您可以使用文字轉換語音來產生音訊檔案。
curl --location --request POST 'https://INSERT_REGION_HERE.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US' \
--header 'Ocp-Apim-Subscription-Key: INSERT_SUBSCRIPTION_KEY_HERE' \
--header 'Content-Type: audio/wav' \
--data-binary @'INSERT_AUDIO_FILE_PATH_HERE'

您應該會收到 JSON 主體的回應,如下列範例所示:

{
    "RecognitionStatus": "Success",
    "DisplayText": "My voice is my passport, verify me.",
    "Offset": 6600000,
    "Duration": 32100000
}

如需詳細資訊,請參閱語音轉換文字 REST API 參考

在本操作指南中,您將瞭解如何實時辨識和轉譯語音到文字。

從麥克風辨識語音

插入並開啟您的電腦麥克風。 關閉任何可能也會使用麥克風的應用程式。 有些計算機有內建麥克風,有些則需要設定 藍牙 裝置。

現在您已準備好執行語音 CLI,以辨識來自麥克風的語音。 從命令行,變更為包含語音 CLI 二進位檔的目錄。 然後執行下列命令:

spx recognize --microphone

注意

語音 CLI 預設為英文。 您可以從語音轉換文字資料表選擇不同的語言。 例如,新增 --source de-DE 以辨識德文語音。

在麥克風中說話,您可以即時看到文字轉譯成文字。 語音 CLI 會在無聲期間後停止,或選取 Ctrl+C 時停止。

從檔案辨識語音

語音 CLI 可以辨識許多檔案格式和自然語言的語音。 在此範例中,您可以使用包含英文語音的任何 .wav 檔案(16 KHz 或 8 KHz、16 位和 mono PCM)。 或者,如果您想要快速範例,請下載 whatstheweatherlike.wav 檔案,並將它複製到與語音 CLI 二進位檔相同的目錄。

使用下列命令執行語音 CLI 來辨識音訊檔案中找到的語音:

spx recognize --file whatstheweatherlike.wav

注意

語音 CLI 預設為英文。 您可以從語音轉換文字資料表選擇不同的語言。 例如,新增 --source de-DE 以辨識德文語音。

語音 CLI 會在畫面上顯示語音的文字轉譯。

執行並使用容器

語音容器會提供 Websocket 型查詢端點 API,其可透過語音 SDK 和語音 CLI 來存取。 根據預設,語音 SDK 和語音 CLI 會使用公用語音服務。 若要使用容器,您必須變更初始化方法。 使用容器主機 URL,而不是金鑰和區域。

如需容器的詳細資訊,請參閱 使用 Docker 安裝和執行語音容器中的主機 URL

下一步