一.功能说明
1. 程序应能够读取MP3,ogg文件,并播放其中的音频。
2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。
3. 程序应具有良好的用户界面,方便用户进行操作。
4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行
二.winform窗体控件设计
通过button控件我们设计“播放ogg文件”“选择歌曲”“停止播放”和“下一首”这四个功能模块,listbox模块的右侧由一个竖着的进度条来控制音量,listbox用于显示我们的音乐播放列表,open file dialog1用于获取音乐文件,同时利用Windows自带的控件axWindowsMediaPlayer控件来实现音乐的播放功能,同时它也具有音乐播放器基本的暂停播放音量调节的作用。
三.代码实现
using NAudio;
using NAudio.Wave;
using NAudio.Vorbis;
using NVorbis.Contracts;
这些 using
声明导入了 NAudio 库中所需的命名空间,以便在代码中直接使用 NAudio 提供的类和接口。
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "选择音频|*.mp3;*.flac;*.wav";
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
localmusicList.Clear();
listBox1.Items.Clear();//清理控件
if (files != null)
{
Array.Clear(files, 0, files.Length);
}//清理文件
files = openFileDialog1.FileNames;
string[] arry = files;
foreach (string x in arry)
{
listBox1.Items.Add(x);
localmusicList.Add(x);
}
}
}
这段代码实现的功能是当用户点击按钮1时,会弹出一个文件选择对话框,用户可以选择一个或多个音频文件。选择完成后,选中的文件会被添加到一个列表框中,并且它们的路径会被存储在 localmusicList
列表中。同时,之前选择的文件列表和路径数组都会被清空,以便存储新的选择。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (localmusicList.Count > 0)
{
int selectedIndex = listBox1.SelectedIndex;
if (selectedIndex >= 0)
{
string selectedFile = localmusicList[selectedIndex];
if (!selectedFile.EndsWith(".ogg"))
{
axWindowsMediaPlayer1.URL = selectedFile;
musicplay(axWindowsMediaPlayer1.URL);
label1.Text = Path.GetFileNameWithoutExtension(se