目录
一、功能说明
- 能够读取mp3,wav,flac,ogg类型的文件并播放。
- 程序能够处理可能出现的异常,如文件不存在、文件读取错误等。
- 程序具有良好的用户界面,方便用户进行操作。
- 能够下载网络音乐。
二、窗体设计
如下图所示
三、代码实现
1、准备工作
axWindowsMediaPlayer无法播放ogg文件,添加NAudio库和NAudio.Vorbis库
2、定义变量
string[] files;//存储音频名称
List<string> localmusiclist = new List<string>();//用于存储多个文件
private WaveOutEvent outputDevice = null;//创建输出设备
private VorbisWaveReader vorbisReader = null;
3、音乐播放方法
private void Musicplay(string filename)
{
try
{
//获取文件扩展名
string extension = Path.GetExtension(filename);
//判断文件后缀名
if (extension == ".ogg")
{
OggDeal(filename);
}
else
{
axWindowsMediaPlayer1.URL = filename;
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}
catch (Exception ex)
{
MessageBox.Show($"无法播放音乐文件 {filename}: {ex.Message}", "播放错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
4、对ogg文件的处理
private void OggDeal(string oggFilePath)
{
try
{
//初始化vorbis格式读取器和输出设备
vorbisReader = new VorbisWaveReader(oggFilePath);
outputDevice = new WaveOutEvent();
outputDevice.Init(vorbisReader);
//开始播放音频
outputDevice.Play();
}
catch (Exception ex)
{
MessageBox.Show($"播放音频文件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
5、添加音乐文件
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "选择音频|*.mp3;*.wav;*.flac;*.ogg";
openFileDialog1.Multiselect = true;//可使用鼠标选取多个文件
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();//清空listbox原有文件
if (files != null)
{
Array.Clear(files, 0, files.Length);//将files清空
}
files = openFileDialog1.FileNames;
string[] array = files;
foreach (string x