How to play an audio file in .NET MAUI

Mane, PRASHANT GORAKH 101 Reputation points
2024-03-01T08:04:45.89+00:00

I want to play a sound on my mobile application (android and IOS)

So I've Added the sound file under the “Resource/Raw” folder with BuildAction=MauiAsset
and Added Nuget package "Plugin.Maui.Audio"

and used below code to play the sound

var audioPlayer = AudioManager.Current.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("myaudio.mp3"));

 audioPlayer.Play();

but I'm getting FileNotFoundException exception.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,411 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 42,001 Reputation points Microsoft Vendor
    2024-03-06T02:41:20.4966667+00:00

    Hello,

    For playing media files, MAUI provides an official solution.

    You could refer to MediaElement, and the following code sample:

    After installing CommunityToolkit.Maui and CommunityToolkit.Maui.MediaElement, you could use the following code to play myaudio.mp3:

                builder
                    .UseMauiApp<App>()
                    .UseMauiCommunityToolkit()
                   .UseMauiCommunityToolkitMediaElement()
    
    
    <toolkit:MediaElement Source="embed://myaudio.mp3" ShouldAutoPlay="True"/>
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.