8

I want to play a sound on my mobile application (android and IOS) I play a sound in certain circumstances. How can I do it?

Emma
  • 431
  • 6
  • 19

4 Answers4

5

Playing AUDIO in MAUI APP Made Easy with 2 Plugins: In NuGet Packages Manager Install Following and Use Dependency Injection After Installation!

  1. Plugin.Maui.Audio: https://www.nuget.org/packages/Plugin.Maui.Audio/0.1.0-preview1?_src=template
  2. Plugin.MauiAudio: https://www.nuget.org/packages/Plugin.MauiAudio/1.0.4?_src=template
5

.NET Maui (feb,2023), still in preview on VS2022.

There is another way to play audio/video (mp3/mp4) in .NET MAUI: MediaElement control of Communitytoolkit (CommunityToolkit.Maui.MediaElement) with support for Android/iOS/Windows/Tizen/Mac. Use NUGet to install.

Put local files in "Resources/Raw" with BuildAction=MauiAsset

Inside a contentPage (xaml/c#)

<toolkit:MediaElement x:Name="correctMediaElement" IsVisible="false"
            Source="embed://crrect_answer2.mp3" />

internal static void PlaySound(MediaElement me)
{
    var preset = MauiProgram.Preset;
    if (me.CurrentState != CommunityToolkit.Maui.Core.Primitives.MediaElementState.Stopped &&
        me.CurrentState != CommunityToolkit.Maui.Core.Primitives.MediaElementState.Paused)
    {
        me.Stop();
    }
    if (preset != null)
    {
        switch (preset.BuzzerVolume)
        {
            case Volume.Off:
                me.Volume = 0.0;
                break;
            case Volume.Low:
                me.Volume = 0.2;
                break;
            case Volume.Medium:
                me.Volume = 0.7;
                break;
            case Volume.High:
                me.Volume = 1.0;
                break;
            default:
                break;
        }
    }

    if (me.Position != TimeSpan.Zero)
    {
        //Will Play sound here
        me.SeekTo(TimeSpan.Zero);
    }
    else if (me.CurrentState != CommunityToolkit.Maui.Core.Primitives.MediaElementState.Playing)
    {
        me.Play();
    }
}

for more information:
MediaElement doc
DevBlogs.Microsoft.com

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
antonio
  • 548
  • 8
  • 16
2

Currently, Maui does not have any audio playback framework. And there are some relative known issues in maui, you can follow them here:

https://github.com/dotnet/maui/issues/7152 .

https://github.com/CommunityToolkit/Maui/issues/113

Thanks for your feedback and support for maui.

Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19
  • This answer might be obsolete. See [antonio's more recent answer](https://stackoverflow.com/a/75468324/199364), which discusses `MediaElement control of Communitytoolkit`. – ToolmakerSteve Jun 17 '23 at 03:04
0

Should use "file:///storage/..." instead of "filesystem:///storage/..." to read local media in android.