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

本文关键字:列表 按钮 文件 mp3 何播放 播放 | 更新日期: 2023-09-27 18:08:40

如何在列表框和按钮中播放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());
          }
        }
    }

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

代码中的几个问题:

你从来没有设置的来源,我假设是一个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需要。您必须使用filename来获取完整路径。

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();
    }
}