背景
把所学的知识做一个沉淀,能拥有属于自己的音乐播放器,通过使用C#实现的播放器包含有一般音乐器的基本功能,如:添加音乐,暂停,播放,下一首,上一首等。
要求1:
1. 程序应能够读取MP3文件,并播放其中的音频。
2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。
3. 程序应具有良好的用户界面,方便用户进行操作。
4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。
提示:此功能可以使用WindowsMediaPlayer控件
要求2:
1. 程序应能够播放ogg文件。
2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。
3. 程序应具有良好的用户界面,方便用户进行操作。
4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。
代码实现
1.设计用户的交互界面
这里我们需要使用的控件有:
1、listBox(显示列表)
2、Windows Music Player(音乐播放器)
3、openFileDialog(导入文件)
4、TrackBar(音量调节)
5、Button(进行操作)
设计的效果图如下:
2.功能实现
1.listBox控件的的代码实现
private void musicplay(string filename)
{
try
{
// 设置URL属性前检查文件是否存在
if (!File.Exists(filename))
{
throw new FileNotFoundException("文件不存在。", filename);
}
// 尝试设置Windows Media Player的URL
axWindowsMediaPlayer1.URL = filename;
// 获取文件扩展名
string extension = Path.GetExtension(filename).ToLower();
// 根据文件扩展名决定播放或输出信息
switch (extension)
{
case ".ogg":
Console.WriteLine("这是.ogg文件");
// 注意:Windows Media Player可能不支持.ogg格式,需要额外的逻辑来处
//理这种情况
break;
case ".mp3":
// 尝试播放MP3文件
axWindowsMediaPlayer1.Ctlcontrols.play();
break;
default:
Console.WriteLine("无法识别的文件格式");
break;
}
}
catch (FileNotFoundException ex)
{
// 处理文件未找到异常
MessageBox.Show($"文件未找到:{ex.FileName}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (COMException ex) // 假设axWindowsMediaPlayer1抛出的是COMException,但具体取决于其实现
{
// 处理COM组件异常,例如Windows Media Player控件相关的问题
MessageBox.Show($"Windows Media Player发生错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex) // 捕获其他所有异常
{
// 处理其他未知异常
MessageBox.Show($"发生未知错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
// 检查列表是否有项,以及索引是否在有效范围内
if (localmusiclist.Count > 0 && listBox1.SelectedIndex >= 0 && listBox1.SelectedIndex < localmusiclist.Count)
{
string selectedFile = localmusiclist[listBox1.SelectedIndex];
// 调用musicplay方法并传入文件路径
musicplay(selectedFile);
// 更新标签文本
label1.Text = Path.GetFileNameWithoutExtension(selectedFile);
}
else
{
// 如果没有选中项或索引无效,可以更新标签或执行其他操作
label1.Text = "未选择音乐";
}
}
catch (IndexOutOfRangeException ex)
{
// 处理索引超出范围的异常(通常不应该发生)
MessageBox.Show("索引超出范围:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex) // 捕获musicplay方法可能抛出的所有其他异常
{
// 处理其他异常
MessageBox.Show("在播放音乐时发生错误:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
2.添加歌曲的功能实现
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "选择音频|*.mp3;*.flac;*.wav";
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
localmusiclist.Clear();
listBox1.Items.Clear();
if (files != null)
{
files = new string[0]; // 初始化数组
}
files = openFileDialog1.FileNames;
foreach (string fileName in files)
{
try
{
listBox1.Items.Add(fileName);
localmusiclist.Add(fileName);
}
catch (Exception ex)
{
MessageBox.Show($"在添加文件 {fileName} 到列表时出错:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
能)
MessageBox.Show($"在处理文件选择时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
3.暂停功能的实现
private bool isPaused = false;
private void button2_Click(object sender, EventArgs e)
{
// 检查当前的播放状态
if (isPaused)
{
// 如果音乐是暂停的,则恢复播放
axWindowsMediaPlayer1.Ctlcontrols.play();
isPaused = false; // 更新状态
}
else
{
// 如果音乐正在播放,则暂停
axWindowsMediaPlayer1.Ctlcontrols.pause();
isPaused = true; // 更新状态
}
}
4.下一曲的实现
private void button3_Click(object sender, EventArgs e)
{
if (localmusiclist.Count > 0 && listBox1.SelectedIndex != -1)
{
// 计算下一个索引,并处理循环到最后一首的情况
int nextIndex = (listBox1.SelectedIndex + 1) % localmusiclist.Count;
// 设置URL并更新UI
axWindowsMediaPlayer1.URL = localmusiclist[nextIndex];
label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[nextIndex]);
// 更新ListBox的选中项
listBox1.SelectedIndex = nextIndex;
}
else
{
// 处理没有歌曲或没有选中歌曲的情况
MessageBox.Show("没有歌曲可供选择。");
}
}
5.播放ogg文件的按钮
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;
try
{
// 尝试使用VorbisWaveReader打开文件
using (var vorbis = new VorbisWaveReader(oggFilePath))
{
using (var waveOut = new WaveOutEvent())
{
try
{
// 尝试初始化WaveOutEvent并播放音频
waveOut.Init(vorbis);
waveOut.Play();
// 使用waveOut.PlaybackStopped事件代替循环等待
waveOut.PlaybackStopped += (s, args) =>{};
while (waveOut.PlaybackState == PlaybackState.Playing)
{
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
// 播放或初始化过程中出现异常
MessageBox.Show("播放或初始化音频时出错:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception ex)
{
// 打开文件或创建VorbisWaveReader时出现异常
MessageBox.Show("打开音频文件时出错:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
6.音量大小控制的实现
private void trackBar1_Scroll(object sender, EventArgs e)
{
axWindowsMediaPlayer1.settings.volume = trackBar1.Value;
label2.Text = trackBar1.Value + "%";
}
完整的代码实现:
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;
using NAudio;
using NAudio.Vorbis;
using NAudio.Wave;
namespace WindowsFormsApp4
{
public partial class Form1 : Form
{
string[] files;//用来存储文件名
//播放列表的信息
List<string> localmusiclist = new List<string> { };
public Form1()
{
InitializeComponent();
}
public void musicplay(string filename)
{
//设置Windows Media Player控件的URL属性为传入的文件名
axWindowsMediaPlayer1.URL = filename;
//获取文件名的扩展名
string extension = Path.GetExtension(filename);
if (extension == ".ogg")
{
Console.WriteLine("这是ogg文件");//输出提示信息
}
else
{
//使用Windows Media Player控件的Ctlcontrols对象的play方法播放
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "选择音频|*mp3;*.wav;*.flac";//设置文件选择对话框的过滤器,只显示支持的音频文件格式。
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[] array = files;//将files变量的值赋给一个新的字符串数组,然后遍历添加
foreach (string x in array)
{
listBox1.Items.Add(x);
localmusiclist.Add(x);
}
}
}
private void axWindowsMediaPlayer1_Enter(object sender, EventArgs e)
{
}
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 button2_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.Ctlcontrols.stop();
}
private void button3_Click(object sender, EventArgs e)
{
if (localmusiclist.Count > 0)
{
int index = listBox1.SelectedIndex + 1;
if (index >= localmusiclist.Count()) { index = 0; }
axWindowsMediaPlayer1.URL = localmusiclist[index];
musicplay(axWindowsMediaPlayer1.URL);
label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[index]);
listBox1.SelectedIndex = index;
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
axWindowsMediaPlayer1.settings.volume = trackBar1.Value;
}
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);
}
}
}
}
}
}