用C#写一个随机音乐播放器

form1中namespce里的代码如下

cs 复制代码
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string folder = textBox1.Text;
        string folderPath = @folder; // 指定音频文件所在的文件夹路径
        OpenRandomFile(folderPath);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    //实际是随机打开一个文件,鉴于VS内置的库不能播放除了wav以外的音频
    private void OpenRandomFile(string folderPath)
    {
        if (!Directory.Exists(folderPath))
        {
            MessageBox.Show("指定的文件夹不存在,请检查路径是否正确。");
            return;
        }

        var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
        if (files.Length == 0)
        {
            MessageBox.Show("文件夹为空或没有可访问的文件。");
            return;
        }

        Random random = new Random();
        int index = random.Next(files.Length);
        string filePath = files[index];

        try
        {
            System.Diagnostics.Process.Start(filePath);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"无法打开文件: {ex.Message}");
        }
    }
}

实际是随机打开一个文件,鉴于VS内置的库不能播放除了wav以外的音频

效果如图

这里的文件夹地址是直接Ctrl+Shift+C复制过来的,注意要去掉引号

exe的链接如下

链接:https://pan.baidu.com/s/105w5fij6kkrUoWcjMuiBWA?pwd=tdo7

提取码:tdo7

相关推荐
晨星shine15 小时前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530141 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526741 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526741 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf5 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530145 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools6 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的6 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21887 天前
.NET 本地Db数据库-技术方案选型
windows·c#