用C#编写一个能实现音乐文件的播放功能的程序

要求1:

1. 程序应能够读取MP3文件,并播放其中的音频。

2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。

3. 程序应具有良好的用户界面,方便用户进行操作。

4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。

提示:此功能可以使用WindowsMediaPlayer控件

要求2:

1. 程序应能够播放ogg文件。

2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。

3. 程序应具有良好的用户界面,方便用户进行操作。

4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。

提示:此功能可以使用Nuget程序包中的Naudi.Vorbis控件

一、准备工作

     首先点击项目(P),点击管理NuGet程序包;然后搜索NAudio、NVorbis这两个程序包,下载完成后点击应用。

二、程序编写

    首先,我们添加一个ListBox1(在工具箱中搜索)放置在From1.cs[设计]中。ListBox1在后续过程中将作为显示歌名的面板。双击ListBox1,进入From1.cs程序编写页面,将以下代码写入。

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         if (localmusiclist.Count > 0)
         {
             axWindowsMediaPlayer1.URL = localmusiclist[listBox1.SelectedIndex];
             musicplay(axWindowsMediaPlayer1.URL);
             label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[listBox1.SelectedIndex]);
         }
     }
     catch(Exception ex)
     {
         MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

     }
 }

    将刚刚下载的第三方库加入到项目中:

using NAudio.Wave;
using NAudio.Vorbis;
using NVorbis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

第二步,从工具箱中搜索label,在From1.cs[设计]中加入两个label,系统自动将其命名为label1、label2,鼠标右键label1然后点击属性,修改label1的Text为音乐播放器,在后续运行中,我们可以发现label1能够显示当前播放音乐的歌名。

第三步,在From1.cs[设计]中加入四个button控件,系统会自动将其命名为button1、button2、button3、button4,分别修改控件Text为添加音乐、停止音乐、下一曲、播放ogg。

以下是各button控件的代码

  private void button1_Click(object sender, EventArgs e)//播放音乐
  {
      try
      {
          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;
              string[] array = files;
              foreach (string x in array)
              {
                  listBox1.Items.Add(x);
                  localmusiclist.Add(x);
              }
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
  }



private void button2_Click(object sender, EventArgs e)//停止音乐
{
    try 
    { axWindowsMediaPlayer1.Ctlcontrols.stop();}
    catch(Exception ex)
    {
        MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void button3_Click(object sender, EventArgs e)//下一曲
{
    try
    {
        int nextIndex = listBox1.SelectedIndex + 1;

        // 如果超出了列表范围,播放第一首音乐
        if (nextIndex >= localmusiclist.Count)
        {
            nextIndex = 0;
        }
        axWindowsMediaPlayer1.URL = localmusiclist[nextIndex];
        musicplay(axWindowsMediaPlayer1.URL);
        label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[nextIndex]);
        listBox1.SelectedIndex = nextIndex;
    }
    catch (Exception ex)
    {
        MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void button4_Click(object sender, EventArgs e)//播放ogg
{
    try
    {
        string oggFilePath;
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "播放音频|*.ogg";
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            oggFilePath = openFileDialog.FileName;
            using (var vorbisReader = new VorbisWaveReader(oggFilePath))
            {
                using (var outputDevice = new WaveOutEvent())
                {
                    outputDevice.Init(vorbisReader);
                    outputDevice.Play();

                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

第四步,音量调节显示

创建一个trackBar1用来调节播放的音量值,以下是它的代码:

private void trackBar1_Scroll(object sender, EventArgs e)
{
    try
    {
        axWindowsMediaPlayer1.settings.volume = trackBar1.Value;
        label2.Text = trackBar1.Value + "%";
    }
    catch (Exception ex)
    {
        MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

第五步,加入音乐播放栏

一般的音乐播放器都有音乐播放栏,VS中有自带的WindowsMediaPlayer控件在工具箱中搜索加入即可。

完整代码如下:

using NAudio.Wave;
using NAudio.Vorbis;
using NVorbis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsMusic1
{
    public partial class Form1 : Form
    {
        string[] files;

        List<string> localmusiclist = new List<string> { };
        public Form1()
        {
            InitializeComponent();
        }
        private void musicplay(string filename)
        {
            string extension = Path.GetExtension(filename);
            if (extension == ".ogg")
            {
                Console.WriteLine("this is ogg file.");
            }
            else
            {
                Console.WriteLine("this is not ogg file.");
                axWindowsMediaPlayer1.Ctlcontrols.play();

            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                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;
                    string[] array = files;
                    foreach (string x in array)
                    {
                        listBox1.Items.Add(x);
                        localmusiclist.Add(x);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (localmusiclist.Count > 0)
                {
                    axWindowsMediaPlayer1.URL = localmusiclist[listBox1.SelectedIndex];
                    musicplay(axWindowsMediaPlayer1.URL);
                    label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[listBox1.SelectedIndex]);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            try
            {
                axWindowsMediaPlayer1.settings.volume = trackBar1.Value;
                label2.Text = trackBar1.Value + "%";
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            try 
            { axWindowsMediaPlayer1.Ctlcontrols.stop();}
            catch(Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int nextIndex = listBox1.SelectedIndex + 1;

                // 如果超出了列表范围,播放第一首音乐
                if (nextIndex >= localmusiclist.Count)
                {
                    nextIndex = 0;
                }
                axWindowsMediaPlayer1.URL = localmusiclist[nextIndex];
                musicplay(axWindowsMediaPlayer1.URL);
                label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[nextIndex]);
                listBox1.SelectedIndex = nextIndex;
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string oggFilePath;
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "播放音频|*.ogg";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    oggFilePath = openFileDialog.FileName;
                    using (var vorbisReader = new VorbisWaveReader(oggFilePath))
                    {
                        using (var outputDevice = new WaveOutEvent())
                        {
                            outputDevice.Init(vorbisReader);
                            outputDevice.Play();

                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                System.Threading.Thread.Sleep(1000);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生异常:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void axWindowsMediaPlayer1_Enter(object sender, EventArgs e)
        {

        }
    }
}

三、运行结果

未添加音乐前

添加音乐后

三、总结

1.在 Form1 类中定义了一个 List<string> 类型的 localmusiclist 变量,用于存储音乐文件的路径。
在 button1_Click 事件处理程序中,使用 OpenFileDialog 对话框让用户选择音频文件,并将选择的文件路径添加到 localmusiclist 中。
2.trackBar1_Scroll 事件处理程序用于调整音量,设置了 axWindowsMediaPlayer1 控件的音量。
3.button2_Click 事件处理程序用于停止当前音乐的播放。
4.button3_Click 事件处理程序用于播放下一首音乐,如果已经是最后一首则循环播放第一首。
5.button4_Click 事件处理程序用于播放选中的 .ogg 格式音频文件,使用了 VorbisWaveReader 和 WaveOutEvent 类来播放该格式的音频文件。
6.try...catch...用来处理可能出现的异常

  • 44
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值