共用方式為


快速入門:使用 Azure OpenAI 在 Microsoft Foundry 模型中的文字轉語音

在此快速入門指南中,您將使用 Azure OpenAI 配合 OpenAI 語音進行文字轉語音。

可用的語音包括:alloyechofableonyxnovashimmer。 如需詳細資訊,請參閱 適用於文字到語音轉換的 Azure OpenAI 參考檔

先決條件

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 檢查來自 Azure 入口網站 的資源時,可以在 [金鑰與端點] 區段中找到服務端點。 或者,你也可以透過 Microsoft Foundry 入口網站的 部署 頁面找到該端點。 範例端點為:https://docs-test-001.openai.azure.com/
AZURE_OPENAI_API_KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [端點和金鑰]。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

此螢幕擷取畫面顯示 Azure 入口網站中某個 Azure OpenAI 資源的概觀 UI,其中標示出端點和存取金鑰位置。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

這很重要

請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果您使用 API 金鑰,請安全地將其儲存在 Azure 金鑰保存庫。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱 使用 Azure Key Vault 的 API 金鑰

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立 REST 要求和回應

在 bash 終端中,執行下列命令。 您必須將 YourDeploymentName 取代為在部署文字轉換語音模型時所選擇的部署名稱。 部署名稱不一定要與模型名稱相同。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。

curl $AZURE_OPENAI_ENDPOINT/openai/deployments/YourDeploymentName/audio/speech?api-version=2025-04-01-preview \
 -H "api-key: $AZURE_OPENAI_API_KEY" \
 -H "Content-Type: application/json" \
 -d '{
    "model": "tts-1-hd",
    "input": "I'm excited to try text to speech.",
    "voice": "alloy"
}' --output speech.mp3

具有範例端點的命令第一行格式將如下 curl 所示:https://aoai-docs.openai.azure.com/openai/deployments/{YourDeploymentName}/audio/speech?api-version=2025-04-01-preview \

這很重要

在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。

原始程式碼 (英文) | 套件 (npm) (英文) | 範例 (英文)

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 synthesis-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir synthesis-quickstart && cd synthesis-quickstart
    
  2. 使用下列命令建立 package.json

    npm init -y
    
  3. 使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:

    npm install openai
    
  4. 若要設定建議的無密碼驗證:

    npm install @azure/identity
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

謹慎

若要搭配 SDK 使用建議的無密鑰驗證,請確定 AZURE_OPENAI_API_KEY 未設定環境變數。

建立語音檔案

  1. 使用下列程式代碼,建立 index.js 檔案。

    const { writeFile } = require("fs/promises");
    const { AzureOpenAI } = require("openai");
    const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");
    require("openai/shims/node");
    
    // You will need to set these environment variables or edit the following values
    const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint";
    const speechFilePath = "<path to save the speech file>";
    
    // Required Azure OpenAI deployment name and API version
    const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "tts";
    const apiVersion = process.env.OPENAI_API_VERSION || "2024-08-01-preview";
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    function getClient() {
      return new AzureOpenAI({
        endpoint,
        azureADTokenProvider,
        apiVersion,
        deployment: deploymentName,
      });
    }
    
    async function generateAudioStream(
      client,
      params
    ) {
      const response = await client.audio.speech.create(params);
      if (response.ok) return response.body;
      throw new Error(`Failed to generate audio stream: ${response.statusText}`);
    }
    export async function main() {
      console.log("== Text to Speech Sample ==");
    
      const client = getClient();
      const streamToRead = await generateAudioStream(client, {
        model: deploymentName,
        voice: "alloy",
        input: "the quick brown chicken jumped over the lazy dogs",
      });
    
      console.log(`Streaming response to ${speechFilePath}`);
      await writeFile(speechFilePath, streamToRead);
      console.log("Finished streaming");
    }
    
    main().catch((err) => {
      console.error("The sample encountered an error:", err);
    });
    
    
  2. 使用下列命令登入 Azure:

    az login
    
  3. 執行 JavaScript 檔案。

    node index.js
    

原始程式碼 (英文) | 套件 (npm) (英文) | 範例 (英文)

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 assistants-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir assistants-quickstart && cd assistants-quickstart
    
  2. 使用下列命令建立 package.json

    npm init -y
    
  3. 請使用下列命令將 package.json 更新為 ECMAScript。

    npm pkg set type=module
    
  4. 使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:

    npm install openai
    
  5. 若要設定建議的無密碼驗證:

    npm install @azure/identity
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

謹慎

若要搭配 SDK 使用建議的無密鑰驗證,請確定 AZURE_OPENAI_API_KEY 未設定環境變數。

建立語音檔案

  1. 使用下列程式代碼,建立 index.ts 檔案。

    import { writeFile } from "fs/promises";
    import { AzureOpenAI } from "openai";
    import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
    import type { SpeechCreateParams } from "openai/resources/audio/speech";
    import "openai/shims/node";
    
    // You will need to set these environment variables or edit the following values
    const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint";
    const speechFilePath = "<path to save the speech file>";
    
    // Required Azure OpenAI deployment name and API version
    const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "tts";
    const apiVersion = process.env.OPENAI_API_VERSION || "2025-04-01-preview";
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    function getClient(): AzureOpenAI {
      return new AzureOpenAI({
        endpoint,
        azureADTokenProvider,
        apiVersion,
        deployment: deploymentName,
      });
    }
    
    async function generateAudioStream(
      client: AzureOpenAI,
      params: SpeechCreateParams
    ): Promise<NodeJS.ReadableStream> {
      const response = await client.audio.speech.create(params);
      if (response.ok) return response.body;
      throw new Error(`Failed to generate audio stream: ${response.statusText}`);
    }
    export async function main() {
      console.log("== Text to Speech Sample ==");
    
      const client = getClient();
      const streamToRead = await generateAudioStream(client, {
        model: deploymentName,
        voice: "alloy",
        input: "the quick brown chicken jumped over the lazy dogs",
      });
    
      console.log(`Streaming response to ${speechFilePath}`);
      await writeFile(speechFilePath, streamToRead);
      console.log("Finished streaming");
    }
    
    main().catch((err) => {
      console.error("The sample encountered an error:", err);
    });
    
    

    在 Node.js 環境中執行程式碼時,必須匯入 "openai/shims/node"。 它可確保 client.audio.speech.create 方法的輸出類型已正確設定為 NodeJS.ReadableStream

  2. 建立檔案 tsconfig.json 以轉譯 TypeScript 程式代碼,並複製 ECMAScript 的下列程式代碼。

    {
        "compilerOptions": {
          "module": "NodeNext",
          "target": "ES2022", // Supports top-level await
          "moduleResolution": "NodeNext",
          "skipLibCheck": true, // Avoid type errors from node_modules
          "strict": true // Enable strict type-checking options
        },
        "include": ["*.ts"]
    }
    
  3. 從 TypeScript 轉譯為 JavaScript。

    tsc
    
  4. 使用下列命令登入 Azure:

    az login
    
  5. 使用下列命令執行程式碼:

    node index.js
    

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 to-speech-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir to-speech-quickstart && cd to-speech-quickstart
    
  2. 使用下列命令建立新的主控台應用程式:

    dotnet new console
    
  3. 使用 dotnet add package 命令安裝 OpenAI .NET 用戶端連結庫:

    dotnet add package Azure.AI.OpenAI
    
  4. 如需使用 Microsoft Entra ID 推薦的無密鑰驗證,請安裝 Azure.Identity 套件:

    dotnet add package Azure.Identity
    
  5. 如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:

    az login
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

執行快速入門

本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您想要使用 API 金鑰,可以將 DefaultAzureCredential 物件取代為 AzureKeyCredential 物件。

AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 

備註

您可以從 GitHub 的 Foundry Tools SDK 存放庫中的 Azure 語音取得範例音訊檔案,例如 wikipediaOcelot.wav

若要執行快速啟動,請遵循下列步驟:

  1. Program.cs 的內容替換為以下代碼,並將佔位元值更新為您自己的值。

    using Azure;
    using Azure.AI.OpenAI;
    using Azure.Identity; // Required for Passwordless auth
    
    var endpoint = new Uri(
        Environment.GetEnvironmentVariable("YOUR_OPENAI_ENDPOINT") ?? throw new ArgumentNullException());
    var credentials = new DefaultAzureCredential();
    
    // Use this line for key auth
    // var credentials = new AzureKeyCredential(
    //    Environment.GetEnvironmentVariable("YOUR_OPENAI_KEY") ?? throw new ArgumentNullException());
    
    var deploymentName = "tts"; // Default deployment name, update with your own if necessary
    var speechFilePath = "YOUR_AUDIO_FILE_PATH";
    
    AzureOpenAIClient openAIClient = new AzureOpenAIClient(endpoint, credentials);
    AudioClient audioClient = openAIClient.GetAudioClient(deploymentName);
    
    var result = await audioClient.GenerateSpeechAsync(
                    "the quick brown chicken jumped over the lazy dogs");
    
    Console.WriteLine("Streaming response to ${speechFilePath}");
    await File.WriteAllBytesAsync(speechFilePath, result.Value.ToArray());
    Console.WriteLine("Finished streaming");
    
  2. 使用 dotnet run Visual Studio 頂端的 命令或執行按鈕執行應用程式:

    dotnet run
    

輸出

應用程式會在您為 speechFilePath 變數指定的位置產生音訊檔案。 播放裝置上的檔案,以聆聽產生的音訊。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

後續步驟