本文介绍了UWP 媒体播放器下一曲目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用媒体元素在 UWP 项目中播放音频,并启用了带有默认情况下不起作用的上一个和下一个按钮的 TransportControls(按下时没有任何反应).如何在这些按钮上获得点击"事件?我不知道如何告诉按钮实际播放下一首"或上一首"曲目.

I am using a Media Element to play audio in a UWP project and have enabled TransportControls with Previous and Next buttons which don't work by default (nothing happens when pressed).How do I get a "Click" event on these buttons? I don't know how to tell the buttons to actually play the "Next" or "Previous" track.

推荐答案

根据您的要求,您可以监听 SystemMediaTransportControls ButtonPressed 事件,然后您可以按下 NextPrevious.有关更多信息,请参阅 处理系统媒体传输控制按钮按下 文档.

For your requirement, you could listen SystemMediaTransportControls ButtonPressed event, then you could get Next or Previous pressed. For more please refer Handle system media transport controls button presses document.

private async void MyMedia_Loaded(object sender, RoutedEventArgs e)
{  
    var control = MyMedia.MediaPlayer.SystemMediaTransportControls;
    control.ButtonPressed += Control_ButtonPressed;
}

async void Control_ButtonPressed(SystemMediaTransportControls sender,
    SystemMediaTransportControlsButtonPressedEventArgs args)
{
    switch (args.Button)
    {
        case SystemMediaTransportControlsButton.Play:
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                mediaElement.Play();
            });
            break;
        case SystemMediaTransportControlsButton.Pause:
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                mediaElement.Pause();
            });
            break;
        default:
            break;
    }
}

请注意,下一个和上一个按钮仅在播放 MediaPlaybackList 时有效.因为,它是内部事件,只有在实际的 MediaPlaybackItem 播放后才会触发.UWP 不提供直接按钮单击事件.如果只想听按钮单击事件.您可以自定义 MediaTransportControls.请参阅此文档.

Please note the next and previous button only works when playing MediaPlaybackList. Because, it is internal event and it only fires after the actual MediaPlaybackItem is played. UWP does not provide straight button click event. If only want listen button click event. you could custom MediaTransportControls. Please refer this document.

public sealed class CustomMediaTransportControls : MediaTransportControls
{
    public CustomMediaTransportControls()
    {
        this.DefaultStyleKey = typeof(CustomMediaTransportControls);
    }

    protected override void OnApplyTemplate()
    {
        Button PreviousTrackButton = GetTemplateChild("PreviousTrackButton") as Button;
        PreviousTrackButton.Click += PreviousTrackButton_Click;


        base.OnApplyTemplate();
    }

    private void PreviousTrackButton_Click(object sender, RoutedEventArgs e)
    {

    }

}

这篇关于UWP 媒体播放器下一曲目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!