快速入門:使用語音 SDK 在 macOS 上以 C++ 辨識語音Quickstart: Recognize speech in C++ on macOS by using the Speech SDK

在本文中,您將建立適用於 macOS 10.13 或更新版本的 C++ 主控台應用程式。In this article, you create a C++ console application for macOS 10.13 and above. 您將使用認知服務語音 SDK,即時從 Mac 的麥克風將語音轉譯為文字。You use the Cognitive Services Speech SDK to transcribe speech to text in real time from your Mac's microphone. 此應用程式是使用適用於 macOS 的語音 SDK 和 Mac 的預設 C++ 編譯器 (例如 g++) 所建置。The application is built with the Speech SDK for macOS and your Mac's default C++ compiler (for example, g++).

必要條件Prerequisites

您需要語音服務訂用帳戶金鑰,才能完成本快速入門。You need a Speech Services subscription key to complete this Quickstart. 您可以免費取得一個金鑰。You can get one for free. 如需詳細資訊,請參閱免費試用語音服務See Try the Speech Services for free for details.

安裝語音 SDKInstall Speech SDK

重要

下載此頁面上的任何「Azure 認知服務的語音 SDK」元件,即表示您知悉其授權。By downloading any of the Speech SDK for Azure Cognitive Services components on this page, you acknowledge its license. 請參閱語音 SDK 的 Microsoft 軟體授權條款See the Microsoft Software License Terms for the Speech SDK.

認知服務語音 SDK 目前的版本為 1.6.0The current version of the Cognitive Services Speech SDK is 1.6.0.

適用於 macOS 的語音 SDK 可從 https://aka.ms/csspeech/macosbinary 以壓縮的架構組合形式下載。The Speech SDK for macOS can be downloaded as a zipped framework bundle from https://aka.ms/csspeech/macosbinary.

下載並安裝 SDK,如下所示:Download and install the SDK as follows:

  1. 選擇語音 SDK 檔案應解壓縮至的目錄,並將 SPEECHSDK_ROOT 環境變數設定為指向該目錄。Choose a directory to which the Speech SDK files should be extracted, and set the SPEECHSDK_ROOT environment variable to point to that directory. 此變數方便在未來命令中參考此目錄。This variable makes it easy to refer to the directory in future commands. 例如,如果您想要在主目錄中使用目錄 speechsdk,請使用類似下列的命令:For example, if you want to use the directory speechsdk in your home directory, use a command like the following:

    export SPEECHSDK_ROOT="$HOME/speechsdk"
    
  2. 在該目錄不存在的情況下建立它。Create the directory if it doesn't exist yet.

    mkdir -p "$SPEECHSDK_ROOT"
    
  3. 下載並解壓縮包含語音 SDK 架構的 .zip 封存:Download and extract the .zip archive containing the Speech SDK framework:

    wget -O SpeechSDK-macOS.zip https://aka.ms/csspeech/macosbinary
    unzip SpeechSDK-macOS.zip -d "$SPEECHSDK_ROOT"
    
  4. 驗證已壓縮套件之最上層目錄的內容:Validate the contents of the top-level directory of the extracted package:

    ls -l "$SPEECHSDK_ROOT"
    

    目錄清單應包含第三方聲明和授權檔案,以及 MicrosoftCognitiveServicesSpeech.framework 目錄。The directory listing should contain the third-party notice and license files, as well as a MicrosoftCognitiveServicesSpeech.framework directory.

新增範例程式碼Add sample code

  1. 建立名為 helloworld.cpp 的 C++ 原始程式檔,然後在其中貼上下列程式碼。Create a C++ source file named helloworld.cpp, and paste the following code into it.

    #include <iostream> // cin, cout
    #include <MicrosoftCognitiveServicesSpeech/speechapi_cxx.h>
    
    using namespace std;
    using namespace Microsoft::CognitiveServices::Speech;
    
    void recognizeSpeech() {
        // Creates an instance of a speech config with specified subscription key and service region.
        // Replace with your own subscription key and service region (e.g., "westus").
        auto config = SpeechConfig::FromSubscription("YourSubscriptionKey", "YourServiceRegion");
    
        // Creates a speech recognizer
        auto recognizer = SpeechRecognizer::FromConfig(config);
        cout << "Say something...\n";
    
        // Performs recognition. RecognizeOnceAsync() returns when the first utterance has been recognized,
        // so it is suitable only for single shot recognition like command or query. For long-running
        // recognition, use StartContinuousRecognitionAsync() instead.
        auto result = recognizer->RecognizeOnceAsync().get();
    
        // Checks result.
        if (result->Reason == ResultReason::RecognizedSpeech) {
            cout << "We recognized: " << result->Text << std::endl;
        }
        else if (result->Reason == ResultReason::NoMatch) {
            cout << "NOMATCH: Speech could not be recognized." << std::endl;
        }
        else if (result->Reason == 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 update the subscription info?" << std::endl;
            }
        }
    }
    
    int main(int argc, char **argv) {
        setlocale(LC_ALL, "");
        recognizeSpeech();
        return 0;
    }
    
  2. 在這個新檔案中,以您的語音服務訂用帳戶金鑰取代 YourSubscriptionKey 字串。In this new file, replace the string YourSubscriptionKey with your Speech Services subscription key.

  3. 以與您的訂用帳戶 (例如,免費試用訂用帳戶的 westus) 相關聯的區域取代 YourServiceRegion 字串。Replace the string YourServiceRegion with the region associated with your subscription (for example, westus for the free trial subscription).

建置應用程式Build the app

注意

請務必以「單一命令行」 的形式輸入下面的命令。Make sure to enter the commands below as a single command line. 若要這麼做,最簡單的方式就是使用每個命令旁邊的 [複製] 按鈕來複製命令,然後將它貼在殼層提示字元。The easiest way to do that is to copy the command by using the Copy button next to each command, and then paste it at your shell prompt.

  • 執行下列命令以建置應用程式。Run the following command to build the application.

    g++ helloworld.cpp -o helloworld --std=c++14 -F${SPEECHSDK_ROOT} -framework MicrosoftCognitiveServicesSpeech
    

執行應用程式Run the app

  1. 將載入程式的程式庫路徑設定為指向語音 SDK 程式庫。Configure the loader's library path to point to the Speech SDK library.

    export DYLD_FRAMEWORK_PATH="$DYLD_FRAMEWORK_PATH:$SPEECHSDK_ROOT"
    
  2. 執行應用程式。Run the application.

    ./helloworld
    
  3. 主控台視窗會出現提示,要求您說一些話。In the console window, a prompt appears, requesting that you say something. 請說英文片語或句子。Speak an English phrase or sentence. 您的語音會傳送到語音服務,並且轉譯為文字,該文字會出現在相同視窗中。Your speech is transmitted to the Speech Services and transcribed to text, which appears in the same window.

    Say something...
    We recognized: What's the weather like?
    

後續步驟Next steps

另請參閱See also