Olá, neste post irei demonstrar como a sua aplicação Xamarin.Forms pode conter um recurso de conversão de textos em voz.
ADICIONANDO O NUGET PACKAGE
Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”.
Digite “Xam.Plugins.TextToSpeech” e selecione o plugin como demonstrado na imagem a seguir.
Selecione todos os projetos e clique no botão “Install”.
XAML
Crie um Entry pare receber o texto digitado e um Button para chamar o método que irá realizar a conversão.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
x:Class="TextToSpeechDemo.MainPage"> | |
<StackLayout VerticalOptions="CenterAndExpand"> | |
<Entry x:Name="Texto"/> | |
<Button Text="Ouvir" Clicked="ButtonClick"/> | |
</StackLayout> | |
</ContentPage> |
C#
Referencie o plugin TextToSpeech, crie o método ButtonClick que será responsável por verificar se existe texto digitado no Entry, se sim, será realizado uma chamada para o método Speak do plugin, passando o texto como parâmetro.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Plugin.TextToSpeech; | |
using Xamarin.Forms; | |
namespace TextToSpeechDemo | |
{ | |
public partial class MainPage : ContentPage | |
{ | |
public MainPage() | |
{ | |
InitializeComponent(); | |
} | |
public async void ButtonClick(object sender, EventArgs e) | |
{ | |
if (!String.IsNullOrWhiteSpace(Texto.Text)) | |
await CrossTextToSpeech.Current.Speak(Texto.Text); | |
} | |
} | |
} |
Pronto, o texto digitado será convertido em voz e reproduzido pelo dispositivo.
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.