动态制作播放列表

时间:2017-08-20 09:50:49

标签: c# wpf

    private Queue<Uri> playList = new Queue<Uri>();

playList.Enqueue(new Uri(@"D:\media1")); playList.Enqueue(new Uri(@"D:\media2")); playList.Enqueue(new Uri(@"D:\media3"));

这里我正在对播放列表进行硬编码。但我想从字符串数组填充playList。怎么可能?

我的字符串数组是string[] mylist=new string[3];

mylist[0]=@"D:\media1;
mylist[1]=@"D:\media2;
mylist[2]=@"D:\media3;

我做到了:

for (int i = 0; i < mylist.Length; i++)
        {
            playList.Enqueue(new Uri(mylist[i]));
            mediaelement.play();

        }

但它只播放最后的媒体.....

1 个答案:

答案 0 :(得分:0)

问题是MediaElement实际上没有播放列表功能,但您可以自己轻松实现。将MediaEndedEvent实现到mediaElement并播放字符串数组中的下一个元素。我的xaml代码:

<Window x:Class="WpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    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="clr-namespace:WpfApp"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="320*"/>
            <RowDefinition Height="50*"/>
        </Grid.RowDefinitions>
        <MediaElement x:Name="mediaelement" Grid.RowSpan="1" LoadedBehavior="Manual" MediaEnded="mediaelement_MediaEnded"/>
        <StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
            <Button x:Name="btnPlay" Content="Next" Click="mediaelement_MediaEnded" Width="50" Height="25" Margin="5"/>
        </StackPanel>
    </Grid>
</Window>

和C#代码:

public partial class MainWindow : Window
{
    private string[] mylist = new string[3];

    public MainWindow()
    {
        InitializeComponent();
        mylist[0] = @"D:\media1";
        mylist[1] = @"D:\media1";
        mylist[2] = @"D:\media1";
        mediaelement.Source = new Uri(mylist[0]);
        mediaelement.Play();
    }

    private void mediaelement_MediaEnded(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < mylist.Length - 1; i++)
        {
            Uri current = new Uri(mylist[i]);
            if (mediaelement.Source == current)
            {
                mediaelement.Source = new Uri(mylist[i + 1]);
                break;
            }
        }

        mediaelement.Play();
    }
}