基于C#实现音乐文件的播放功能

  using NAudio.Wave;

  using NAudio.Vorbis;

  namespace WindowsFormsApp3

  {

  public partial class Form1 : Form

  {

  string[] files;

  List localmusiclist = new List{};

  public Form1()

  {

  InitializeComponent();

  }

  private void musicplay(string filename)

  {

  string extension = Path.GetExtension(filename);//fanhuiwenjiandekuozhanhouzhuiming

  if (extension == ".ogg") { Console.WriteLine("这是ogg文件"); }

  else

  {

  Console.WriteLine("这不是ogg文件");

  axWindowsMediaPlayer1.Ctlcontrols.play();

  }

  }

  private void button1_Click(object sender, EventArgs e)

  {

  openFileDialog1.Filter = "选择音频|*mp3;*.wav;*.flac";

  openFileDialog1.Multiselect = true;

  if (openFileDialog1.ShowDialog() == DialogResult.OK)

  {

  listBox1.Items.Clear();//将新文件导入,将原文件清空

  if (files != null)

  {

  Array.Clear(files, 0, files.Length);

  }

  files = openFileDialog1.FileNames;//因为filenames必须为数组

  string[] array = files;

  foreach (string x in array)

  {

  listBox1.Items.Add(x);

  localmusiclist.Add(x);

  }

  }

  }

  private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

  {

  if (localmusiclist.Count > 0)

  {

  axWindowsMediaPlayer1.URL = localmusiclist[listBox1.SelectedIndex];

  musicplay(axWindowsMediaPlayer1.URL);

  label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[listBox1.SelectedIndex]);

  }

  }

  private void trackBar1_Scroll(object sender, EventArgs e)

  {

  axWindowsMediaPlayer1.settings.volume = trackBar1.Value;

  label2.Text=trackBar1.Value+"%";

  }

  private void button2_Click(object sender, EventArgs e)

  {

  axWindowsMediaPlayer1.Ctlcontrols.stop();

  }

  private void button3_Click(object sender, EventArgs e)

  {

  int nextIndex= listBox1.SelectedIndex;

  if (localmusiclist.Count > 0)

  {

  if (listBox1.SelectedIndex + 1 > localmusiclist.Count)

  {

  nextIndex = 0;

  }

  axWindowsMediaPlayer1.URL = localmusiclist[nextIndex];

  musicplay(axWindowsMediaPlayer1.URL);

  label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[nextIndex]);

  listBox1.SelectedIndex = nextIndex;

  }

  }

  private void button4_Click(object sender, EventArgs e)

  {

  string oggFilePath="";

  OpenFileDialog openFileDialog = new OpenFileDialog();

  openFileDialog.Filter = "播放音频|*.ogg";

  if(openFileDialog.ShowDialog() == DialogResult.OK)

  {

  oggFilePath =openFileDialog.FileName;

  }

  using (var vorbis = new VorbisWaveReader(oggFilePath))

  {

  using (var waveOut = new WaveOutEvent())

  {

  waveOut.Init(vorbis);

  waveOut.Play();

  while(waveOut.PlaybackState == PlaybackState.Playing)

  {

  System.Threading.Thread.Sleep(1000);

  }

  }

  }

  }

  }

  }