更改源后,UWP播放MediaElement

时间:2019-11-27 09:07:05

标签: c# uwp

我希望被称为播放器的MediaElement在指定其源之后播放mp3:

private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            player.Stop();
            player.Source = new Uri("ms-appx:///Assets/anata.mp3");
            player.Play();
        }

但是它不起作用,并且没有错误显示。我该怎么办?

这是原始问题和完整代码:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:cvt="using:App1"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <cvt:MusicConverter x:Key="mc"/>
    </Page.Resources>

    <Viewbox Visibility="Visible" Margin="20">
        <Grid x:Name="root" Height="1000" Width="1800">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="2.5*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="0.15*"/>
                <RowDefinition Height="0.15*"/>
            </Grid.RowDefinitions>
            <Rectangle Grid.Row="0" Grid.Column="0" Height="150" Fill="#FF4187A9" VerticalAlignment="Top"/>
            <MediaElement x:Name="player" MediaFailed="player_MediaFailed" Grid.Column="1" Grid.Row="0" Margin="20" VerticalAlignment="Center" Source="Assets/bad_apple.mp4" AutoPlay="false" MediaOpened="Player_Opened" MediaEnded="Player_ended"/>
            <Slider x:Name="controller" Value="{Binding ElementName=player, Path=Position, Converter={StaticResource mc}, Mode=TwoWay}" Grid.Column="1" Grid.Row="1" Height="50" Width="1000" Minimum="0" Maximum="100" VerticalAlignment="Center"  />
            <Button RequestedTheme="Dark" FontFamily="Segoe MDL2 Assets" Content="&#xE112;" Grid.Column="1" Grid.Row="2" Height="75" Width="75" Margin="449,0,0,0" Click="Button_Click_3"/>
            <Button RequestedTheme="Dark" FontFamily="Segoe MDL2 Assets" Content="&#xE111;" Grid.Column="1" Grid.Row="2" Height="75" Width="75" Margin="750,0,0,0" Click="Button_Click_2"/>
            <Button x:Name="playButton" RequestedTheme="Dark" Grid.Column="1" Grid.Row="2" Height="75" Width="75" HorizontalAlignment="Center" Click="Button_Click_1">
                <SymbolIcon x:Name="ppp" Symbol="Play" />
            </Button>
            <Slider x:Name="vol" StepFrequency="0.05" Minimum="0.0" Maximum="1.0" SmallChange="0.05" LargeChange="0.1" Value="0.5" Grid.Column="1" Grid.Row="2" Height="30" Width="100" Margin="1019,42,167,43" ValueChanged="Slider_ValueChanged"/>
            <ToggleSwitch x:Name="repeatButton" Grid.Row="2" Grid.Column="1"  OnContent="repeat on" OffContent="repeat off" IsOn="False" Margin="45,0,0,0"/>
            <TextBlock Grid.Row="0" Grid.Column="0" VerticalAlignment="Top" Text="PlayList" FontSize="72" Grid.ColumnSpan="2" Margin="140,27,1146,0"/>
            <Rectangle Grid.Row="0" Grid.Column="1" Margin="20" StrokeThickness="2" Stroke="#ffffff"/>
            <ListBox x:Name="lst" SelectedIndex="0" Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" Margin="0,155,0,0" SelectionChanged="ListBox_SelectionChanged">
                <TextBlock Text="Bad Apple" FontSize="50" />
                <TextBlock Text="Anata" FontSize="50" />
                <TextBlock Text="Wind" FontSize="50" />
            </ListBox>
        </Grid>
    </Viewbox>

</Page>

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace App1
{
    class MusicConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return ((TimeSpan)value).TotalSeconds;
        }
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return TimeSpan.FromSeconds((double)value);
        }
    }
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            MediaElement mediaElement = new MediaElement();
            var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
            Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("button");
            mediaElement.SetSource(stream, stream.ContentType);
            mediaElement.Play();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int sel = lst.SelectedIndex;
            string videoName;
            switch (sel)
            {
                case 0:
                    videoName = "bad_apple.mp4"; break;
                case 1:
                    videoName = "anata.mp3"; break;
                case 2:
                    videoName = "Wind.mp3"; break;
                default:
                    videoName = "bad_apple.mp4"; break;
            }
            player.Source = new Uri("ms-appx:///Assets/" + videoName);

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (player.CurrentState.ToString()=="Paused")
            {
                player.Play();
                ppp.Symbol = Windows.UI.Xaml.Controls.Symbol.Pause;
                Debug.WriteLine(player.CurrentState.ToString());
            }
            else
            {
                player.Pause();
                ppp.Symbol = Windows.UI.Xaml.Controls.Symbol.Play;
                Debug.WriteLine(player.CurrentState.ToString());
            }

        }

        private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            player.Volume = (double)vol.Value;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
            Debug.WriteLine(player.CurrentState.ToString());
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            lst.SelectedIndex = (lst.SelectedIndex - 1) < 0 ? lst.Items.Count - 1 : lst.SelectedIndex - 1;
        }
        private void Player_Opened(object sender, RoutedEventArgs e)
        { 
            controller.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
        }
        private void Player_ended(object sender, RoutedEventArgs e)
        {

            if (repeatButton.IsOn)
            {
                player.Play();
            }
            else
            {
                lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
                int sel = lst.SelectedIndex;
                string videoName;
                switch (sel)
                {
                    case 0:
                        videoName = "bad_apple.mp4"; break;
                    case 1:
                        videoName = "anata.mp3"; break;
                    case 2:
                        videoName = "Wind.mp3"; break;
                    default:
                        videoName = "bad_apple.mp4"; break;
                }
                player.Source = new Uri("ms-appx:///Assets/" + videoName);
                player.Play();
            }
            player.Play();
        }

        private void player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            string msg = e.ErrorMessage;
            Debug.WriteLine(msg);
        }
    }
}

主要问题是Player_ended。我希望此播放器在repeatButton打开时可以重复播放,并在关闭时自动播放下一个mp3。但这行不通。 Source已成功更改为新的Uri,但是代码player.Play()似乎被忽略了。我必须单击playButton才能播放。我简化了代码,然后出现了一个新问题,该问题显示在顶部。

1 个答案:

答案 0 :(得分:0)

请检查以下内容:

  1. 检查计算机是否已打开声音

  2. 检查音乐文件的网址是否正确(以及该文件是否可以由其他播放器播放)

如果一切正常,则可以收听MediaElement.MediaFailed事件。如果触发,则表明音乐文件可能异常。您可以从事件中获取有关错误的更多信息。

private void player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
    string msg = e.ErrorMessage;
    Debug.WriteLine(msg);
}

顺便说一句,在Windows 10中,内部版本1607,我们建议您使用MediaPlayerElement代替MediaElementMediaPlayerElement具有与MediaElement相同的功能,同时还支持更高级的媒体播放方案。此外,未来所有媒体播放方面的改进都将在MediaPlayerElement中实现。


更新

代码的问题是您在错误的时间调用了Play()方法。

设置player的来源后,player将进入 Opening 状态。在Play()处于此状态的情况下调用player时,播放器将无法播放音频,并且在加载音乐文件后,播放器自然会进入Pause状态。

因此,您可以在player.Play()的末尾删除Player_ended方法,只需设置player.AutoPlay = True;

像这样:

private void Player_ended(object sender, RoutedEventArgs e)
{

    if (repeatButton.IsOn)
    {
        player.Play();
    }
    else
    {
        lst.SelectedIndex = (lst.SelectedIndex + 1) % lst.Items.Count;
        player.AutoPlay = true;
    }
}

顺便说一句,当您修改lst.SelectedIndex时,也会触发ListBox_SelectionChanged事件,您不必在Player_ended中再次调用它。

最诚挚的问候。