

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Amazon Polly 合成語音範例
<a name="synthesize-example"></a>

此頁面顯示使用 Python 在主控台、 AWS CLI和 中執行的簡短語音合成範例。此範例會從純文字而非 SSML 執行語音合成。

------
#### [ Console ]

**在主控台上合成語音**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/polly/](https://console.aws.amazon.com/polly/) 的 Amazon Polly 主控台。

1. 選擇 **Text-to-Speech** (文字轉換語音) 索引標籤。文字欄位將載入範例文字，讓您可以快速試用 Amazon Polly。

1. 關閉 **SSML**。

1. 輸入此文字或將其貼到輸入方塊。

   ```
   He was caught up in the game. In the middle of the 10/3/2014 W3C meeting he shouted, "Score!" quite loudly.
   ```

1. 在**引擎**下，選擇**生成式**、**長形**、**神經**或**標準**。

1. 選擇語言和 AWS 區域，然後選擇語音。（如果您為**引擎**選取**神經**，則只有支援 NTTS 的語言和語音可用。 所有標準和長形語音都會停用。)

1. 若要立即接聽語音，請選擇**接聽**。

1. 若要將語音儲存至檔案，請執行以下其中一項：

   1. 選擇 **Download** (下載)。

   1. 若要變更為不同的檔案格式，請展開**其他設定**、開啟**語音檔案格式設定**、選擇您想要的檔案格式，然後選擇**下載**。

------
#### [ AWS CLI ]

在本練習中，您可以透過傳遞輸入文字來呼叫 `SynthesizeSpeech`操作。您可以將產生的音訊儲存為檔案並驗證其內容。

1. 執行 `synthesize-speech` AWS CLI 命令，將範例文字合成到音訊檔案 (`hello.mp3`)。

   下列 AWS CLI 範例已針對 Unix、Linux 和 macOS 格式化。對於 Windows，將每一行尾端的反斜線 (\$1) Unix 接續字元取代為插入符號 (^)，並在輸入文字周圍使用完整引號 (") 取代內部標籤的單引號 (')。

   ```
   aws polly synthesize-speech \
       --output-format mp3 \
       --voice-id Joanna \
       --text 'Hello, my name is Joanna. I learned about the W3C on 10/3 of last year.' \
       hello.mp3
   ```

   在呼叫 時`synthesize-speech`，您可以提供範例文字，以您選擇的語音合成。您必須提供語音 ID （在下列步驟中說明） 和輸出格式。命令會將產生的音訊儲存至 `hello.mp3` 檔案。除了 MP3 檔案，此操作會將以下輸出傳送到主控台。

   ```
   {
           "ContentType": "audio/mpeg", 
           "RequestCharacters": "71"
   }
   ```

1. 播放產生的 `hello.mp3` 檔案，以驗證合成的語音。

------
#### [ Python ]

若要測試 Python 範例程式碼，您需要 適用於 Python (Boto) 的 AWS SDK。如需相關指示，請參閱[適用於 Python (Boto3) 的 AWS SDK](https://aws.amazon.com/sdk-for-python/)。

此範例中的 Python 程式碼會執行下列動作：
+ 叫用 適用於 Python (Boto) 的 AWS SDK 將`SynthesizeSpeech`請求傳送至 Amazon Polly （透過提供一些文字做為輸入）。
+ 存取回應中產生的音訊串流，並將音訊儲存至本機磁碟上的檔案 (`speech.mp3`) 。
+ 使用本機系統的預設音訊播放器播放音訊檔案。

將程式碼儲存至檔案 (example.py) 並執行。

```
"""Getting Started Example for Python 2.7+/3.3+"""
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import os
import sys
import subprocess
from tempfile import gettempdir

# Create a client using the credentials and region defined in the [adminuser]
# section of the AWS credentials file (~/.aws/credentials).
session = Session(profile_name="adminuser")
polly = session.client("polly")

try:
    # Request speech synthesis
    response = polly.synthesize_speech(Text="Hello world!", OutputFormat="mp3",
                                        VoiceId="Joanna")
except (BotoCoreError, ClientError) as error:
    # The service returned an error, exit gracefully
    print(error)
    sys.exit(-1)

# Access the audio stream from the response
if "AudioStream" in response:
    # Note: Closing the stream is important because the service throttles on the
    # number of parallel connections. Here we are using contextlib.closing to
    # ensure the close method of the stream object will be called automatically
    # at the end of the with statement's scope.
        with closing(response["AudioStream"]) as stream:
           output = os.path.join(gettempdir(), "speech.mp3")

           try:
            # Open a file for writing the output as a binary stream
                with open(output, "wb") as file:
                   file.write(stream.read())
           except IOError as error:
              # Could not write to file, exit gracefully
              print(error)
              sys.exit(-1)

else:
    # The response didn't contain audio data, exit gracefully
    print("Could not stream audio")
    sys.exit(-1)

# Play the audio using the platform's default player
if sys.platform == "win32":
    os.startfile(output)
else:
    # The following works on macOS and Linux. (Darwin = mac, xdg-open = linux).
    opener = "open" if sys.platform == "darwin" else "xdg-open"
    subprocess.call([opener, output])
```

------

如需深入範例的詳細資訊，請參閱下列主題：
+ [在主控台上使用 SSML](ssml-to-speech-console.md) 
+ [套用語彙 （合成語音）](managing-lexicons-console-synthesize-speech.md) 
+ [Amazon Polly 的範例程式碼和應用程式](samples-and-examples.md) 