KeiStory

.NET MAUI Audio/Music 재생하기

 

1. "Plugin.Maui.Audio" Nuget Pakcage 설치

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 - jfversluis/Plugin.Maui.Audio

github.com

2. mp3 파일 넣기

Resources > Raw 폴더에 mp3 파일을 추가합니다.

 

3. 화면 정의 및 ViewModel

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.AudioTest.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="White">
    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            IsVisible="{Binding IsLoadComplete}"
            Spacing="25"
            VerticalOptions="Center">

            <Label
                HorizontalOptions="Center"
                Text="Audio Test"
                TextColor="Black" />
            <Label
                HorizontalOptions="Center"
                Text="{Binding Status, StringFormat=[ {0} ]}"
                TextColor="Black" />

            <HorizontalStackLayout HorizontalOptions="Center" Spacing="15">
                <Button
                    BackgroundColor="Black"
                    Command="{Binding PlayCommand}"
                    HeightRequest="50"
                    SemanticProperties.Hint="Start playing"
                    Text="▶"
                    TextColor="White"
                    WidthRequest="50" />

                <Button
                    BackgroundColor="Black"
                    Command="{Binding PauseCommand}"
                    FontAttributes="Bold"
                    HeightRequest="50"
                    SemanticProperties.Hint="Pause playing"
                    Text="||"
                    TextColor="White"
                    WidthRequest="50" />

                <Button
                    BackgroundColor="Black"
                    Command="{Binding StopCommand}"
                    HeightRequest="50"
                    SemanticProperties.Hint="Stop playing"
                    Text="■"
                    TextColor="White"
                    WidthRequest="50" />
            </HorizontalStackLayout>

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

MainPage.xaml.cs

using Maui.AudioTest.ViewModels;

namespace Maui.AudioTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            BindingContext = new MainViewModel();
        }
    }
}

MainViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

using Plugin.Maui.Audio;

namespace Maui.AudioTest.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        #region Fields
        private IAudioManager audioManager;
        private IAudioPlayer audioPlayer;

        private bool isLoadComplete = false;
        public bool IsLoadComplete
        {
            get
            {
                return this.isLoadComplete;
            }
            set
            {
                this.isLoadComplete = value;
                NotifyPropertyChanged();
            }
        }


        private string status = "Wait";
        public string Status
        {
            get
            {
                return this.status;
            }
            set
            {
                this.status = value;
                NotifyPropertyChanged();
            }
        }

        public Command PlayCommand { get; set; }
        public Command PauseCommand { get; set; }
        public Command StopCommand { get; set; }

        protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        // Constructor
        #region MainViewModel
        public MainViewModel()
        {
            this.audioManager = new AudioManager();

            SetMusic();

            PlayCommand = new Command(OnPlayCommand);
            PauseCommand = new Command(OnPauseCommand);
            StopCommand = new Command(OnStopCommand);
        }
        #endregion

        #region SetMusic
        /// <summary>
        /// Play 될 음악 파일을 설정합니다.
        /// </summary>
        private async void SetMusic()
        {
            audioPlayer = audioManager.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("motive.mp3"));

            if (audioPlayer != null)
            {
                IsLoadComplete = true;
            }
        }
        #endregion

        #region OnPlayCommand
        void OnPlayCommand()
        {
            audioPlayer.Play();
            Status = "Play";
        }
        #endregion
        #region OnPauseCommand
        void OnPauseCommand()
        {
            if (audioPlayer.IsPlaying)
            {
                audioPlayer.Pause();
                Status = "Pause";
            }
            else
            {
                audioPlayer.Play();
                Status = "Play";
            }
        }
        #endregion
        #region OnStopCommand
        void OnStopCommand()
        {
            if (audioPlayer.IsPlaying)
            {
                audioPlayer.Stop();
                Status = "Stop";
            }
        }
        #endregion
    }
}

위 코드를 보면 알수 있듯이  Play, Pause, Stop 버튼에 따라 음악이 컨트롤되고

음악의 재생 상태가 상단에 표시됩니다.

 

실행화면


실행영상

 

소스

https://github.com/kei-soft/Maui.AudioTest

 

GitHub - kei-soft/Maui.AudioTest

Contribute to kei-soft/Maui.AudioTest development by creating an account on GitHub.

github.com

 

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band