共用方式為


文字轉換語音

流覽範例。 流覽範例

本文說明如何使用 .NET 多平臺應用程式 UI (.NET MAUI) ITextToSpeech 介面。 此介面可讓應用程式使用內建的文字轉語音引擎來朗讀裝置內的文字。 您也可以使用它來查詢可用的語言。

介面的預設實作 ITextToSpeech 可透過 TextToSpeech.Default 屬性取得。 ITextToSpeech介面和TextToSpeech類別都包含在Microsoft.Maui.Media命名空間中。

開始

若要存取文字到語音轉換功能,需要下列平臺特定設定。

如果您的項目目標 Android 版本設定為 Android 11(R API 30) 或更高版本,您必須使用文字到語音轉換引擎的意圖篩選來更新 Android 指令清單 。 如需意圖的詳細資訊,請參閱 Android 關於 意圖和意圖篩選的檔。

[平臺/Android/AndroidManifest.xml ] 檔案中,將下列 queries/intent 節點新增至 manifest 節點:

<queries>
  <intent>
    <action android:name="android.intent.action.TTS_SERVICE" />
  </intent>
</queries>

使用文字轉換語音

文字到語音轉換的運作方式是使用文字來呼叫 SpeakAsync 方法,如下列程式代碼範例所示:

public async void Speak() =>
    await TextToSpeech.Default.SpeakAsync("Hello World");

此方法會接受選擇性的 CancellationToken 以在語句開始後停止語句。

CancellationTokenSource cts;

public async Task SpeakNowDefaultSettingsAsync()
{
    cts = new CancellationTokenSource();
    await TextToSpeech.Default.SpeakAsync("Hello World", cancelToken: cts.Token);

    // This method will block until utterance finishes.
}

// Cancel speech if a cancellation token exists & hasn't been already requested.
public void CancelSpeech()
{
    if (cts?.IsCancellationRequested ?? true)
        return;

    cts.Cancel();
}

文字轉換語音會自動將來自相同執行緒的語音要求排入佇列。

bool isBusy = false;

public void SpeakMultiple()
{
    isBusy = true;

    Task.WhenAll(
        TextToSpeech.Default.SpeakAsync("Hello World 1"),
        TextToSpeech.Default.SpeakAsync("Hello World 2"),
        TextToSpeech.Default.SpeakAsync("Hello World 3"))
        .ContinueWith((t) => { isBusy = false; }, TaskScheduler.FromCurrentSynchronizationContext());
}

設定

若要控制聲音的音量、音調和地區設定,請使用 類別 SpeechOptions 。 將該類別的實例傳遞至 SpeakAsync(String, SpeechOptions, CancellationToken) 方法。 方法 GetLocalesAsync() 會擷取作業系統所提供的地區設定集合。

public async void SpeakSettings()
{
    IEnumerable<Locale> locales = await TextToSpeech.Default.GetLocalesAsync();

    SpeechOptions options = new SpeechOptions()
    {
        Pitch = 1.5f,   // 0.0 - 2.0
        Volume = 0.75f, // 0.0 - 1.0
        Locale = locales.FirstOrDefault()
    };

    await TextToSpeech.Default.SpeakAsync("How nice to meet you!", options);
}

以下是這些參數支援的值:

參數 最小值 最大值
Pitch 0 2.0
Volume 0 1.0

若要控制語音的音量、音調、速率和地區設定,請使用 SpeechOptions 類別。 將該類別的實例傳遞至 SpeakAsync(String, SpeechOptions, CancellationToken) 方法。 方法 GetLocalesAsync() 會擷取作業系統所提供的地區設定集合。

public async void SpeakSettings()
{
    IEnumerable<Locale> locales = await TextToSpeech.Default.GetLocalesAsync();

    SpeechOptions options = new SpeechOptions()
    {
        Pitch = 1.5f,   // 0.0 - 2.0
        Volume = 0.75f, // 0.0 - 1.0
        Rate = 1.5f,    // 0.1 - 2.0
        Locale = locales.FirstOrDefault()
    };

    await TextToSpeech.Default.SpeakAsync("How nice to meet you!", options);
}

以下是這些參數支援的值:

參數 最小值 最大值
Pitch 0 2.0
Volume 0 1.0
Rate 0.1 2.0

限制

  • 如果在多個線程中進行呼叫,語音佇列無法得到保證。
  • 背景音訊播放功能並未被正式支援。