개발노트

25. [.NET MAUI] AudioPlayer 로 소리 재생하기 본문

앱 개발/.NET MAUI

25. [.NET MAUI] AudioPlayer 로 소리 재생하기

mroh1226 2022. 9. 15. 09:50
반응형

.NET MAUI에 드디어 Sound File을 재생할 수 있는 누겟(NuGet)이 배포되었다.

 

이를 가지고 <TapGestureRecognizer>에 소리를 넣어보는 예제를 만들어 본다.

 

- 참고링크: https://www.youtube.com/watch?v=oIYnEuZ9oew 


준비물 세팅

 

1. NuGet 패키지 관리자에 들어간다.

도구 &rarr; NuGet 패키지 관리자 &rarr; 솔루션용 NuGet 패키지 관리

 

2. Plugin.Maui.Audio를 검색하여 설치한다. (시험판)

 

Plugin.Maui.Audio 설치

 

사용할 mp3나 wav 파일을 Raw에 넣음


- 시나리오: StartPage.xaml에 있는 <Fram>을 Tap하면 소리와함께 고양이가 회전한다.

 

3. <Frame>에<GestureRecognizers> 을 통해<TapGestureRecognizer> ViewModel에서 구현할 cmd_Tapping를 바인딩시킨다. <CommandParameter>는 클릭된 고양이(Frame)가 회전하기 위해 넣은 것이라 안해도 무방하다.

 

StartPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:skia = "clr-namespace:SkiaSharp.Extended.UI.Controls;assembly=SkiaSharp.Extended.UI"
             xmlns:vm ="clr-namespace:MyMAUI.ViewModels"
             xmlns:service ="clr-namespace:MyMAUI.Services"
             x:Class="MyMAUI.Views.StartPage"
             Title="StartPage">
    
    <Grid 
        RowDefinitions="*,*,*"
        ColumnDefinitions="*">

        <Frame Grid.Row="0" Grid.RowSpan="2" Grid.Column="0">
            <Frame.GestureRecognizers>
                <TapGestureRecognizer Command="{Binding cmd_Tapping}"
                                      CommandParameter="{x:Reference skia}"/>
            </Frame.GestureRecognizers>
            <skia:SKLottieView x:Name="skia"
            Source="cat_loader.json"
            RepeatCount="-1"
            HorizontalOptions="Center"
            VerticalOptions="StartAndExpand"/>
        </Frame>

        <Frame Grid.Row="2" Grid.Column="0">
            <Label 
            Text="고양이를 만져주세요."
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
        </Frame>

    </Grid>
</ContentPage>

 

 


4. StartPage.xaml.cs 에 ViewModel로 사용할 StartVM 을 BindingContext로 지정한다.

StartPage.xaml.cs
using MyMAUI.ViewModels;
namespace MyMAUI.Views;

public partial class StartPage : ContentPage
{
	public StartPage()
	{
		InitializeComponent();
		this.BindingContext = new StartVM();
	}
}

 


5. IAudioManager와 IAudioPlayer를 생성해주고 IAudioManager를 통해 사운드 파일이 입력된 Player를 생성하여 IAudioPlayer에 넣어준다.

 

6. IAudioPlayer의 Play() 메소드를 통해 재생시킨다.


StartVM.cs
using MyMAUI.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MyMAUI.Views;
using SkiaSharp.Extended.UI.Controls;
using Plugin.Maui.Audio;

namespace MyMAUI.ViewModels
{
    class StartVM : Notify
    {
        private IAudioManager audioManager;
        private IAudioPlayer audioPlayer;
        public ICommand cmd_Tapping{ get; set; }
        
        public StartVM()
        {
            cmd_Tapping = new Command(async(obj) =>
            {
                this.audioManager = new AudioManager();
                //Sound File을 지정한다 반드시 Raw에 넣을것!(이유는 이전에 Lottie 파일을 넣을 때 설명했다.)
                audioPlayer = audioManager.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("sound_pop.mp3"));
                audioPlayer.Play();

                SKLottieView skia = (SKLottieView)obj;
                await skia.ScaleTo(0);
                await skia.ScaleTo(2);
                Task task1 = skia.RotateTo(3600,1500);
                Task task2 = skia.ScaleTo(0,1500);
                Task task3 = Task.Delay(1500);

                await Task.WhenAll(task1, task2, task3);
                await Shell.Current.GoToAsync("//App/QuizPage");
            });
        }
    }

}

 

*Play() 메소드 이외에도 IAudioPlayer에 사용가능한 이벤트, 속성, 메소드는 아래와 같다.

 

AudioPlayer

Once you have created an AudioPlayer you can interact with it in the following ways:

Events

PlaybackEnded

Raised when audio playback completes successfully.

Properties

Balance

Gets or sets the balance left/right: -1 is 100% left : 0% right, 1 is 100% right : 0% left, 0 is equal volume left/right.

CanSeek

Gets a value indicating whether the position of the loaded audio file can be updated.

CurrentPosition

Gets the current position of audio playback in seconds.

Duration

Gets the length of audio in seconds.

IsPlaying

Gets a value indicating whether the currently loaded audio file is playing.

Volume

Gets or sets the playback volume 0 to 1 where 0 is no-sound and 1 is full volume.

Loop

Gets or sets whether the player will continuously repeat the currently playing sound.

Methods

Pause()

Pause playback if playing (does not resume).

 

Play()

Begin playback or resume if paused.

 

Seek(double position)

Set the current playback position (in seconds).

 

Stop()

Stop playback and set the current position to the beginning.

 

- GitHub 링크: https://github.com/jfversluis/Plugin.Maui.Audio

 

GitHub - jfversluis/Plugin.Maui.Audio: Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI application

Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI application - GitHub - jfversluis/Plugin.Maui.Audio: Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI ...

github.com


Gif 라서 소리가 안나오지만 실제로는 잘나옴

반응형
Comments