C#:实现音乐文件的播放功能

目录

前言

1.要求一

2.要求二

一、设计思路

三、窗体设计

1.设计样式

2.控件功能

四、代码实现及结果截图

1.定义变量

2..mp3等文件播放实现

3.Button1实现:选择歌曲

​编辑

4.ListBox1实现:播放列表

​编辑

5.Button2实现:暂停

6.Button3实现:下一首

​编辑

7.TrackBar1实现:调节音量

​编辑

8.Button4实现:播放ogg文件

五、总结

1.完整代码

前言

1.要求一

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

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

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

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

2.要求二

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

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

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

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

一、设计思路

使用Windows Forms作为用户界面,使用WindowsMediaPlayer控件播放MP3文件,使用Naudi.Vorbis控件播放ogg文件,设计界面,包括播放、暂停、停止等控件,接着处理异常情况,包括文件不存在、文件读取错误等,最后测试程序在不同版本的C#环境中运行是否正常,确保兼容性。

二、难点分析

1.需要使用WindowsMediaPlayer的COM组件,并了解其方法、属性及如何加载和播放音频文件

添加过程如下:

在Visual Studio中,点击视图中的工具箱,在工具箱中右键单击,选择“选择项”,在弹出的窗口中切换到“COM组件”,下滑列表找出“Windows Media Player”组件,勾选该组件并点击确定将其添加到工具箱中。

2.需要安装并使用Nuget程序包,了解如何加载和播放ogg文件

安装过程如下:

在Visual Studio中选择“工具”菜单下的“NuGet包管理器”,然后选择“管理解决方案的NuGet程序包”。这将打开一个窗口,其中列出了可用的NuGet包。在搜索框中输入“Naudi.Vorbis”,找到对应的包后,点击“安装”以将其添加。

3.需要对文件读取、格式不支持等异常情况进行有效处理,并给出错误提示

三、窗体设计

1.设计样式

2.控件功能

(1)Button:与用户交互,用于触发事件或执行操作。此题中用于实现选择歌曲文件、暂停播放、选择下一首播放的功能。

(2)Label:用于显示文本和图像。此题中用于显示当前播放歌曲。

(3)AxWindowsMediaPlayer:一个ActiveX控件,用于播放音频和视频文件。此题中用于播放MP3等格式的文件(不适用于OGG文件)。

(4)ListBox:用于显示一组选项,用户可以从中选择一个或多个选项。此题中用于展示选择的歌曲列表。

(5)TrackBar:用于调整数值或进度,通常用于控制音量、亮度等设置。此题中用于控制音量(音量设定值为0-100)。

(6)OpenFileDialog:用于文件选择的控件。此题中用于选择音乐文件。

四、代码实现及结果截图

1.定义变量

string[] files;//用来存储文件名

//播放列表的信息
List<string> localmusiclist=new List<string> { };

2..mp3等文件播放实现

URL属性被设置为传入的文件名,是因为该文件名包含了要播放的音乐文件的路径或位置信息。通过将URL属性设置为这个文件名,Windows Media Player控件可以加载并播放指定的音乐文件。

将文件的扩展名单独提取到extension中,通过区分文件格式来选择相应的播放方法。

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();
    }
            
}

3.Button1实现:选择歌曲

设置文件选择对话框的过滤器,只显示支持的音频文件格式(mp3,wav,flac),用户可以选择多个文件。如果用户点击了“确定”按钮,则先清空本地音乐列表和列表框,将选中的文件添加到播放列表和列表框。

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);
                }
            }
        }

仅显示出后缀名为.mp3/.wav/.flac的文件

4.ListBox1实现:播放列表

首先确保歌单里有音乐。如果有音乐,更新Windows Media Player控件的URL属性,并播放选中的音乐。同时更新标签的文本为当前选中的音乐文件名(不包括扩展名)。

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]);
            }
        }

5.Button2实现:暂停

调用Windows Media Player控件的Ctlcontrols对象的stop方法停止播放当前音乐。

private void button2_Click(object sender, EventArgs e)
        {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
        }

6.Button3实现:下一首

如果有音乐,将列表框的选中项切换到下一首音乐,并播放选中的音乐。同时更新标签的文本为当前选中的音乐文件名(不包括扩展名)。

​
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;
            }
        }

​

7.TrackBar1实现:调节音量

根据滑块的值设置Windows Media Player控件的音量。

private void trackBar1_Scroll(object sender, EventArgs e)
{
    axWindowsMediaPlayer1.settings.volume = trackBar1.Value;
}

8.Button4实现:播放ogg文件

设置文件选择对话框的过滤器,只显示ogg文件。如果用户点击了“确定”按钮,使用NAudio库的VorbisWaveReader类读取选中的ogg文件,并使用WaveOutEvent类播放该文件。

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);
                    }
                }
            }
        }

五、总结

1.完整代码

代码地址:用C#实现音乐播放器 · Issue #I9MWQK · cyx-0818/Windows程序设计 - Gitee.com

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);
                    }
                }
            }
        }
    }
}
  • 19
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值