要求1:
1. 程序应能够读取MP3文件,并播放其中的音频。
2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。
3. 程序应具有良好的用户界面,方便用户进行操作。
4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。
提示:此功能可以使用WindowsMediaPlayer控件
要求2:
1. 程序应能够播放ogg文件。
2. 程序应能够处理可能出现的异常,如文件不存在、文件读取错误等。
3. 程序应具有良好的用户界面,方便用户进行操作。
4. 程序应具有良好的兼容性,能在不同版本的C#中正常运行。
提示:此功能可以使用Nuget程序包中的Naudi.Vorbis控件
一、实现原理
对于要求一,使用WindowsMediaPlayer来实现,使程序能够播放MP3文件,以及读取文件夹。
对于要求二,使用Nuget程序包中Naudi.Vorbis的控件,是程序能够播放ogg文件。
二、程序窗口界面
添加音乐:可以添加mp3文件,或者文件夹。
停止音乐:中断程序,不再播放音乐。
下一曲:能够在选中文件夹中的顺序下一首音乐。
播放ogg:能够添加ogg格式的音乐并且播放。
三、代码实现
添加音乐
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "选择音频|*mp3;*.wav;*.fllac";
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);
}
}
}
停止音乐
private void button2_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.Ctlcontrols.stop();
}
下一曲
private void button3_Click(object sender, EventArgs e)
{
if (localmusiclist.Count > 0)
{
if (listBox1.SelectedIndex + 1 > localmusiclist.Count)
{
axWindowsMediaPlayer1.URL = localmusiclist[0];
}
axWindowsMediaPlayer1.URL = localmusiclist[listBox1.SelectedIndex+1];
musicplay(axWindowsMediaPlayer1.URL);
label1.Text = Path.GetFileNameWithoutExtension(localmusiclist[listBox1.SelectedIndex]);
}
}
播放ogg
private void button4_Click(object sender, EventArgs e)
{
string oggFilePath = "path_to_your_ogg_file.ogg"; // 替换为您的OGG文件路径
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);
}
}
}
}
文件展示box
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 + "%";
}
其他代码
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();
}
}