分享方式:


如何辨識語音

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

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

建立語音設定

若要使用語音 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 執行個體。 然後藉由傳遞 speechConfigaudioConfig 來初始化 SpeechRecognizer 物件。

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),將 AudioStreamFormat 物件傳遞至 CreatePushStream()
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 安裝及執行語音容器中的 Host URLs

變更處理無聲的方式

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

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

您可以藉由在用來建立 SpeechRecognizerSpeechConfig 執行個體上設定兩個逾時屬性之一,來解決這些問題:

  • 分段無聲逾時會調整目前讀出的片語被視為「完成」之前允許的非語音音訊數量。
    • 較高的的值通常會讓結果更長,並允許在片語內對說話者進行較長的暫停,但讓結果需要較長的時間才能到達。 設定太高時,也可以將個別的片語結合成單一結果。
    • 較低的值通常會使結果較短,並確保片語之間能更及時且頻繁地中斷,但若設得太低,也可能將單一片語分成多個結果。
    • 此逾時可設定為 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");

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

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

建立語音設定

若要使用語音 SDK 來呼叫語音服務,您必須建立 SpeechConfig 執行個體。 此類別包含訂閱的相關資訊,例如您的金鑰和關聯的位置/區域、端點、主機或授權權杖。

  1. 使用您的金鑰和區域來建立 SpeechConfig 執行個體。
  2. Azure 入口網站上建立語音資源。
using namespace std;
using namespace Microsoft::CognitiveServices::Speech;

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

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

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

注意

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

從麥克風辨識語音

若要使用您的裝置麥克風辨識語音,請使用 FromDefaultMicrophoneInput() 成員函數建立 AudioConfig 執行個體。 然後藉由傳遞 audioConfigconfig 來初始化 SpeechRecognizer 物件。

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.
    });

設定好所有項目後,請呼叫 StartContinuousRecognitionAsync 以開始辨識:

// 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 安裝及執行語音容器中的 Host URLs

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

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

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

使用下列程式碼範例,從預設裝置麥克風執行語音辨識。 以您的語音金鑰和位置/區域分別取代變數 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 入口網站上建立語音資源。 另外,以 .wav 檔的路徑取代變數 file。 您執行指令碼時會從檔案辨識語音,並輸出文字結果:

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 安裝及執行語音容器中的 Host URLs

參考檔 | 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 執行個體。 然後藉由傳遞 audioConfigconfig 來初始化 SpeechRecognizer 物件。

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 安裝及執行語音容器中的 Host URLs

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

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

建立語音設定

若要使用語音 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 安裝及執行語音容器中的 Host URLs

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

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

安裝語音 SDK 和範例

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

如需詳細資訊,請參閱適用於 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 安裝及執行語音容器中的 Host URLs

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

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

安裝語音 SDK 和範例

Azure-Samples/cognitive-services-speech-sdk 存放庫會包含以 Swift 撰寫的範例,適用於 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 安裝及執行語音容器中的 Host URLs

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

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

建立語音設定

若要使用語音 SDK 來呼叫語音服務,您必須建立 SpeechConfig 執行個體。 此類別包含訂閱的相關資訊,例如您的語音金鑰和關聯的位置/區域、端點、主機或授權權杖。

  1. 使用您的語音金鑰和位置/區域來建立 SpeechConfig 執行個體。
  2. Azure 入口網站上建立語音資源。
speech_config = speechsdk.SpeechConfig(subscription="YourSpeechKey", region="YourSpeechRegion")

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

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

注意

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

從麥克風辨識語音

若要使用您的裝置麥克風辨識語音,建立 SpeechRecognizer 執行個體後傳遞 speech_config,無需傳遞 AudioConfig

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 時停止連續識別。 請記住以下幾點:

  • 接收到 evt 時,會列印 evt 訊息。
  • 接收到 evt 後,會呼叫 stop_continuous_recognition() 以停止辨識。
  • 辨識狀態會變更為 True
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 安裝及執行語音容器中的 Host URLs

語音轉換文字 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 安裝及執行語音容器中的 Host URLs

下一步