【问题标题】:How to play text to speech using xamarin.essential如何使用 xamarin.essential 播放文本到语音
【发布时间】:2022-11-29 10:49:56
【问题描述】:

我想播放文本到语音,但我无法使用 Xamarin.essential 听到任何声音。我确定我的智能手机没有静音。编码:

    using Xamarin.Essential


   private void PlayTextMethod()
   {
     if(do sth)
     {
      SpeekFrommethodAsync();
     }

   }

    
    private async SpeekFrommethodAsync()
    {
        await TextToSpeech.SpeakAsync(Tasklabel.Text, new SpeechOptions
        {
            Volume = 1f
        });
    }
      

【问题讨论】:

  • 你在什么平台上测试?您是否遵循了任何特定于平台的设置?
  • 平台是安卓
  • 安卓a52银河
  • 外部设备
  • 不是电脑模拟器

标签: forms xamarin


【解决方案1】:

如果您的项目的目标 Android 版本设置为 Android 11 (R API 30), 打开 Properties 文件夹下的 AndroidManifest.xml 文件并在清单节点中添加以下内容:

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

并在你的方法中试试这个:

 public async Task SpeakNow()
 {
   var locales = await TextToSpeech.GetLocalesAsync();

   // Grab the first locale
   var locale = locales.FirstOrDefault();

   var settings = new SpeechOptions()
    {
        Volume = .75f,
        Pitch = 1.0f,
        Locale = locale
    };

   await TextToSpeech.SpeakAsync("Hello World", settings);
 }

参考:https://learn.microsoft.com/en-us/xamarin/essentials/text-to-speech?context=xamarin%2Fandroid&tabs=android

【讨论】:

  • 我有安卓12.0
【解决方案2】:

我做了一个演示,我在 Android 12 模拟器上测试了它。我发现Text-to-speech函数无法读取属于另一个国家的文字。所以我添加了一个选择器来选择国家。

这是 MainPage.xaml 中的代码

 <StackLayout>
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label Text="Text to speech sample!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
        </Frame>
        <Picker x:Name="Languages"></Picker>
        <Entry x:Name="TextToSpeak"></Entry>
        <Button Text="Speak Please" Clicked="Button_Clicked"></Button>
 </StackLayout>

这是 MainPage.xaml.cs 中的代码。

using Xamarin.Essentials;

  public partial class MainPage : ContentPage
    {

        IEnumerable<Locale> locales;
        public MainPage()
        {
            InitializeComponent();
            
        }
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            locales = await TextToSpeech.GetLocalesAsync();

            foreach(var locale in locales)
            {
                Languages.Items.Add(locale.Name);
            }
                

        }
        private void Button_Clicked(object sender, EventArgs e)
        {
            if(Languages.SelectedIndex > 0)
            {
                TextToSpeech.SpeakAsync(TextToSpeak.Text, new SpeechOptions
                {
                    Locale = locales.Single(locales=> locales.Name == Languages.SelectedItem.ToString())
                });
            }
        }
    }

这是项目的视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多