如何播放音频文件 - .NET MAUI

Emm*_*mma 10 .net c# maui

我想在我的移动应用程序(Android 和 IOS)上播放声音 我在某些情况下播放声音。我该怎么做?

小智 7

使用 2 个插件在 MAUI 应用程序中播放音频变得轻松: 在 NuGet 包管理器中安装以下内容并在安装后使用依赖项注入!

  1. 插件.Maui.Audiohttps://www.nuget.org/packages/Plugin.Maui.Audio/
  2. 插件.MauiAudiohttps://www.nuget.org/packages/Plugin.MauiAudio/


ant*_*nio 5

.NET Maui(2023 年 2 月),仍在 VS2022 上预览。

在 .NET MAUI 中还有另一种播放音频/视频 (mp3/mp4) 的方法: Communitytoolkit 的MediaElement控件,支持 Android/iOS/Windows/Tizen/Mac。

使用NuGet安装,搜索“ CommunityToolkit.Maui.MediaElement ”。

使用 BuildAction=MauiAsset 将本地文件放入“Resources/Raw”中

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Run Code Online (Sandbox Code Playgroud)

在 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息:
MediaElement 文档
DevBlogs.Microsoft.com