配置NuGet包已经更新

https://www.cnblogs.com/dalgleish/p/18967204

使用自己写的MediaElement

https://www.cnblogs.com/dalgleish/p/19012473

PlayMediaTest.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="using:AvaloniaUI"
        Height="300" Width="300"
        x:Class="AvaloniaUI.PlayMediaTest"
        Title="PlayMediaTest">
    <StackPanel Name="LayoutRoot" Margin="10">
        <Button Content="Click to Play Sound" HorizontalAlignment="Left" Padding="5" Margin="3">
            <Interaction.Behaviors>
                <EventTriggerBehavior EventName="Click">
                    <local:PlaySoundAction Source="avares://AvaloniaUI/Resources/Sounds/test.mp3"/>
                </EventTriggerBehavior>
            </Interaction.Behaviors>
        </Button>
    </StackPanel>
</Window>

PlayMediaTest.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using Avalonia.Xaml.Interactivity;
using Shares.Avalonia;
using System;

namespace AvaloniaUI;
public class PlaySoundAction : AvaloniaObject, IAction
{
    public static readonly StyledProperty<Uri> SourceProperty =
        AvaloniaProperty.Register<PlaySoundAction, Uri>(nameof(Source));

    public Uri Source
    {
        get => GetValue(SourceProperty);
        set => SetValue(SourceProperty, value);
    }

    public object? Execute(object? sender, object? parameter)
    {
        if (sender is Control control)
        {
            var container = FindContainer(control);
            if (container != null && Source != null)
            {
                var media = new MediaElement
                {
                    Source = Source,
                    AutoPlay = true,
                };

                media.MediaEnded += (s, e) =>
                {
                    container.Children.Remove(media);
                };

                container.Children.Add(media);
            }
        }
        return null;
    }

    private Panel? FindContainer(Control? element)
    {
        while (element != null)
        {
            if (element is Panel p)
                return p;
            element = element.Parent as Control;
        }
        return null;
    }
}
public partial class PlayMediaTest : Window
{
    public PlayMediaTest()
    {
        InitializeComponent();
    }
}

运行效果

image

 

posted on 2025-09-02 08:18  dalgleish  阅读(17)  评论(0)    收藏  举报