如何在列表框和按钮中播放mp3文件?

时间:2015-08-18 23:00:05

标签: c# wpf

如何在列表框和按钮中播放mp3文件?我尝试过多,但我做不到。当我点击按钮1-2和列表框我的代码中断。

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        media1.Play();
    }

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        media1.Stop();
    }

    private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        media1.Play();
    }

    private void btn010_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog open1 = new  Microsoft.Win32.OpenFileDialog();
        open1.DefaultExt = ".mp3";
        open1.Filter = "(.mp3)|*.mp3";
        open1.Multiselect = true;

        Nullable<bool> result = open1.ShowDialog();

        if(result == true)
        {
          for ( int i = 0; i < open1.SafeFileNames.Length; i++)
          {
              listbox4.Items.Add(open1.SafeFileNames[i].ToString());
          }
        }
    }

1 个答案:

答案 0 :(得分:0)

您的代码几乎没有问题:

你永远不会设置我认为是MediaElement的来源:

private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //This plays the MediaElement, but it doesn't have a Source to play yet!
    //media1.Play();

    //Instead, let's set the Source:
    if (listbox4.SelectedItem != null)
    {
        media1.Source = new Uri(listbox4.SelectedItem.ToString(), UriKind.RelativeOrAbsolute);
    }
}

您使用的是SafeFileNames,它只提供文件名(例如MyFile.mp3),而不是路径(例如C:\ Music \ MyFile.mp3) MediaElement需要的。您必须使用FileNames来获取完整路径。

private void btn010_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog open1 = new  Microsoft.Win32.OpenFileDialog();
    open1.DefaultExt = ".mp3";
    open1.Filter = "(.mp3)|*.mp3";
    open1.Multiselect = true;

    Nullable<bool> result = open1.ShowDialog();

    if(result == true)
    {
        //Can't get the full path from SafeFileNames:
        //for ( int i = 0; i < open1.SafeFileNames.Length; i++)
        //{
        //    listbox4.Items.Add(open1.SafeFileNames[i].ToString());
        //}

        //Instead, we get the full path from FileNames:
        for ( int i = 0; i < open1.FileNames.Length; i++)
        {
            listbox4.Items.Add(open1.FileNames[i].ToString());
        }
    }
}

这应该会使您的程序正常运行。如果您希望它通过曲目列表自动播放,您需要处理MediaElement的MediaEnded事件:

private void media1_MediaEnded(object sender, RoutedEventArgs e)
{
    //If a track finishes, check if there are more tracks and 
    //increment to the next one if so.
    if (listbox4.Items.Count > listbox4.SelectedIndex + 1)
    {
        listbox4.SelectedIndex++;
        media1.Play();
    }
}