【C#】实现对音乐文件的播放功能(windows程序设计课程作业二)

一、作业内容

请编写一个C#程序,实现音乐文件的播放功能。

要求1:

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

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

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

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

提示:此功能可以使用WindowsMediaPlayer控件

要求2:

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

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

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

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

提示:此功能可以使用Nuget程序包中的NAudi.Vorbis控件

二、相关控件

        1、WindowsMediaPlayer控件

        WindowsMediaPlayer控件是微软公司出品的一款媒体播放器控件,通常用于在Windows操作系统和某些开发环境中播放音频和视频文件。在这次的实验中,Windows Media Player控件用于播放音频。操作如下:通过Visual Studio的“工具箱”->“左键点击”->“选择工具箱项”->“COM组件”->“WindowsMediaPlayer”来添加,如图:

再将工具箱常规中的Windows Media Player拖入Form1.cs[设计]中使用,如图:

        2、Nuget程序包中的NAudi.Vorbis控件

        Nuget程序包中的NAudi.Vorbis控件在本次实验中用于读取和播放 Ogg Vorbis 格式的音频文件。安装步骤:“工具箱”->“左键点击”->“Nuget包管理器”->“点击管理解决方案的Nuget程序包”->“搜索NAudi.Vorbis和NAudio(如下图)”进行安装。

 三、代码介绍

        1、定义了两个变量:字符串数组 files和字符串类型的列表 localmusiclistlocalmusiclist 是一个字符串类型的列表,使用集合初始化器将其初始化为一个空列表。

string[] files;

List<string> localmusiclist = new List<string> { };

         2、定义了一个名为 musicplay 的私有方法,该方法接受一个字符串参数 filename。这个方法的目的是尝试使用 axWindowsMediaPlayer1 控件来播放指定的音频文件。

private void musicplay(string filename)
{
    axWindowsMediaPlayer1.URL = filename;
    string extension = Path.GetExtension(filename);

    if(extension == ".ogg") { Console.WriteLine("这是ogg文件。"); }
    else
    { axWindowsMediaPlayer1.Ctlcontrols.play(); }
    
}

        3、一个事件处理器,用于处理listBox1控件的SelectedIndexChanged事件,检查localmusiclist中是否包含元素,并进行相关处理。

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

         4、选择歌曲。选择具有.mp3.flac.wav扩展名的音频文件歌曲,将歌曲添加到listBox1的项集合中以及localmusiclist列表中。

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[] array = files;
        foreach(string x in array) 
        { 
            listBox1.Items.Add(x);
            localmusiclist.Add(x);

        }
    }
}

        5、调节音量。trackBar1是一个滑块控件(TrackBar),通常用于允许用户调整某个范围的值。在这段代码中,用来调整axWindowsMediaPlayer1的音量。

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

        6、停止播放。停止axWindowsMediaPlayer1控件中当前正在播放的音频。

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

        7、下一曲。切换到listBox1中下一个音乐文件(如果已经是最后一个文件,则循环到第一个文件),并更新相关的元素(包括axWindowsMediaPlayer1label1listBox1)以反映当前播放的音乐文件。

private void button3_Click(object sender, EventArgs e)
{
    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;
}

        8、播放ogg。选择一个.ogg格式的音频文件,并使用VorbisWaveReaderWaveOutEvent来播放该音频文件。

private void button4_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "打开音频|*.ogg";

    string oggFilePath = "";

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        oggFilePath = openFileDialog.FileName;
    }

    using (var vorbisReader = new VorbisWaveReader(oggFilePath))
    {
        using (var outputDevice = new WaveOutEvent())
        {
            // 创建WaveOutEvent实例来播放音频  
            outputDevice.Init(vorbisReader);
            outputDevice.Play();

            // 等待播放完成,或者您可以根据需要添加其他逻辑  
            while (outputDevice.PlaybackState == PlaybackState.Playing)
            {
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

四、用户界面

         根据上面的代码介绍进行理解。

五、代码实现

        首先运行代码,如图:

        1、播放MP3音频文件 

         点击“选择歌曲”,添加歌曲,如图:

        点击歌曲进行播放,如下图,也可以点击“停止播放”、“下一曲”、音量调节进行其他操作。

        2、播放ogg音频文件

        点击“播放ogg”,添加歌曲(如图),点击“打开”,自动播放歌曲。

六、小结

        在本次的实验中,通过创建一个WindowsFormsApp项目,在其中下载了一个音频播放器控件(AxWindowsMediaPlayer控件),实现了音频MP3音乐文件的播放功能;使用Nuget程序包中的NAudi.Vorbis控件,实现了播放.ogg格式的音乐文件。通过这次实验,我也深刻体会到了使用第三方库和控件的便利性和重要性。NAudio.Vorbis控件的功能强大且易于使用,提供了对Ogg Vorbis音频格式的支持,允许我在Windows Forms应用程序中直接播放这种格式的音频文件。

        用户界面:用户界面(UI)设计是一个至关重要的环节。用户界面不仅是用户与应用程序交互的桥梁,更是提升用户体验、增强应用程序吸引力的关键。在设计过程中,我尽量保持界面的简洁性,只保留必要的元素,并确保这些元素的功能和位置都是直观易懂的,同时,也注重色彩搭配、字体选择等视觉元素的处理,尽量让界面看起来更加美观舒适。

七、完整代码

https://gitee.com/tang-jingwena/windows-learning/issues/I9N845

using NAudio;
using NAudio.Wave;
using NAudio.Vorbis;
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;

namespace WindowsFormsApp4._23
{
    public partial class Form1 : Form
    {

        string[] files;

        List<string> localmusiclist = new List<string> { };

        public Form1()
        {
            InitializeComponent();
        }

        private void musicplay(string filename)
        {
            axWindowsMediaPlayer1.URL = filename;
            string extension = Path.GetExtension(filename);

            if(extension == ".ogg") { Console.WriteLine("这是ogg文件。"); }
            else
            { axWindowsMediaPlayer1.Ctlcontrols.play(); }
            
        }

        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 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[] array = files;
                foreach(string x in array) 
                { 
                    listBox1.Items.Add(x);
                    localmusiclist.Add(x);

                }
            }
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

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

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

        private void button3_Click(object sender, EventArgs e)
        {
            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 label1_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "打开音频|*.ogg";

            string oggFilePath = "";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                oggFilePath = openFileDialog.FileName;
            }

            using (var vorbisReader = new VorbisWaveReader(oggFilePath))
            {
                using (var outputDevice = new WaveOutEvent())
                {
                    // 创建WaveOutEvent实例来播放音频  
                    outputDevice.Init(vorbisReader);
                    outputDevice.Play();

                    // 等待播放完成,或者您可以根据需要添加其他逻辑  
                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            }
        }
    }
}
  • 10
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值