Olá, neste artigo irei demonstrar como implementar um gravador de áudio em suas aplicações Xamarin.Forms.
ADICIONANDO O NUGET PACKAGE
Para o exemplo será utilizado o plugin AudioRecorder, instale o plugin em todos os seus projetos (Compartilhado / Android / iOS).
Android
Para a plataforma Android, adicione as permissões no arquivo AndroidManifest, como demonstrado a seguir.
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"?> | |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="br.com.julianocustodo.audiodemo"> | |
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" /> | |
<application android:label="AudioDemo.Android"></application> | |
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> | |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> | |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> | |
<uses-permission android:name="android.permission.RECORD_AUDIO" /> | |
</manifest> |
No arquivo MainActivity, adicione uma verificação de permissão no método OnCreate, antes da chamada do método LoadApplication.
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 Android.App; | |
using Android.Content.PM; | |
using Android.Runtime; | |
using Android.OS; | |
using Android.Support.V4.Content; | |
using Android.Support.V4.App; | |
using Android; | |
namespace AudioDemo.Droid | |
{ | |
[Activity(Label = "AudioDemo", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] | |
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity | |
{ | |
protected override void OnCreate(Bundle savedInstanceState) | |
{ | |
TabLayoutResource = Resource.Layout.Tabbar; | |
ToolbarResource = Resource.Layout.Toolbar; | |
base.OnCreate(savedInstanceState); | |
Xamarin.Essentials.Platform.Init(this, savedInstanceState); | |
global::Xamarin.Forms.Forms.Init(this, savedInstanceState); | |
//Verifica se tem permissão | |
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.RecordAudio) != Permission.Granted) | |
{ | |
ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.RecordAudio }, 1); | |
} | |
LoadApplication(new App()); | |
} | |
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) | |
{ | |
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); | |
base.OnRequestPermissionsResult(requestCode, permissions, grantResults); | |
} | |
} | |
} |
iOS
Para a plataforma iOS edite o arquivo Info.plist e adicione a permissão como demonstrado a seguir.
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
… | |
<key>NSMicrophoneUsageDescription</key> | |
<string>The AudioDemo wants to use your microphone to record audio.</string> | |
</dict> | |
</plist> |
XAML
Para este exemplo, crie um Switch que será utilizado como opção para parar a gravação após um determinado tempo de silêncio. Crie também um Button para acionar a gravação e um Button para reproduzir o audio gravado.
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" | |
xmlns:local="clr-namespace:AudioDemo" | |
x:Class="AudioDemo.MainPage" Padding="20,80,20,0"> | |
<StackLayout Spacing="15"> | |
<StackLayout Orientation="Horizontal"> | |
<Switch x:Name="TimeoutSwitch" IsToggled="True" /> | |
<Label Text="Parar após silêncio?" /> | |
</StackLayout> | |
<Button x:Name="GravarButton" | |
Text="Gravar" | |
Clicked="Gravar_Clicked"/> | |
<Button x:Name="ReproduzirButton" | |
Text="Reproduzir" | |
Clicked="Reproduzir_Clicked" | |
IsEnabled="False" /> | |
</StackLayout> | |
</ContentPage> |
C#
Referencie o plugin AudioRecorder e crie um objeto do tipo AudioRecorderService que será utilizado para gravar, e um objeto do tipo AudioPlayer que será utilizado para reproduzir o áudio captado na gravação. Instancie os objetos como demonstrado a seguir.
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 System.ComponentModel; | |
using Plugin.AudioRecorder; | |
using Xamarin.Forms; | |
namespace AudioDemo | |
{ | |
[DesignTimeVisible(true)] | |
public partial class MainPage : ContentPage | |
{ | |
AudioRecorderService gravador; | |
AudioPlayer reprodutor; | |
public MainPage() | |
{ | |
InitializeComponent(); | |
gravador = new AudioRecorderService | |
{ | |
StopRecordingAfterTimeout = true, | |
TotalAudioTimeout = TimeSpan.FromSeconds(15), | |
AudioSilenceTimeout = TimeSpan.FromSeconds(2) | |
}; | |
reprodutor = new AudioPlayer(); | |
reprodutor.FinishedPlaying += Finaliza_Reproducao; | |
} | |
public async void Gravar_Clicked(object sender, EventArgs e) | |
{ | |
} | |
public async void Reproduzir_Clicked(object sender, EventArgs e) | |
{ | |
} | |
public void Finaliza_Reproducao(object sender, EventArgs e) | |
{ | |
} | |
} | |
} |
Gravar
O método para gravar neste exemplo terá duas funções.
- Se não estiver gravando, começar a gravar.
- Se estiver gravando, parar de gravar.
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
public async void Gravar_Clicked(object sender, EventArgs e) | |
{ | |
try | |
{ | |
if (!gravador.IsRecording) | |
{ | |
gravador.StopRecordingOnSilence = TimeoutSwitch.IsToggled; | |
GravarButton.IsEnabled = false; | |
ReproduzirButton.IsEnabled = false; | |
//Começar gravação | |
var audioRecordTask = await gravador.StartRecording(); | |
GravarButton.Text = "Parar Gravação"; | |
GravarButton.IsEnabled = true; | |
await audioRecordTask; | |
GravarButton.Text = "Gravar"; | |
ReproduzirButton.IsEnabled = true; | |
} | |
else | |
{ | |
GravarButton.IsEnabled = false; | |
//parar a gravação… | |
await gravador.StopRecording(); | |
GravarButton.IsEnabled = true; | |
} | |
} | |
catch (Exception ex) | |
{ | |
await DisplayAlert("Erro", ex.Message, "OK"); | |
} | |
} |
Reproduzir
O método reproduzir, ficará encarregado de pegar o audio do objeto gravador e reproduzi-lo, utilizando o método Play do objeto chamado reprodutor.
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
public async void Reproduzir_Clicked(object sender, EventArgs e) | |
{ | |
try | |
{ | |
var filePath = gravador.GetAudioFilePath(); | |
if (filePath != null) | |
{ | |
ReproduzirButton.IsEnabled = false; | |
GravarButton.IsEnabled = false; | |
reprodutor.Play(filePath); | |
} | |
} | |
catch (Exception ex) | |
{ | |
await DisplayAlert("Erro", ex.Message, "OK"); | |
} | |
} |
Finalizar
O método de finalização é responsável apenas em liberar os botões novamente.
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
public void Finaliza_Reproducao(object sender, EventArgs e) | |
{ | |
ReproduzirButton.IsEnabled = true; | |
GravarButton.IsEnabled = true; | |
} |
Resultado
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.
Excelente artigo. Muito claro.
Obrigado
CurtirCurtir