用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

相关推荐
脚踏实地皮皮晨15 分钟前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
十年磨剑走天涯18 分钟前
C++ STL 容器操作复杂度速查表
开发语言·c++
always_TT25 分钟前
【Python requirements.txt 依赖管理】
开发语言·python
15Moonlight34 分钟前
C++进阶(09):特殊类设计
开发语言·c++
宁风NF40 分钟前
JavaScript:网络请求与前端通信
开发语言·前端·javascript·网络·学习·ecmascript
Logintern091 小时前
py文件开头为什么需要加:from __future__ import annotations
开发语言·python
caishenzhibiao1 小时前
降雨带波段点差 同花顺期货通指标
java·c语言·c#
techdashen1 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang
rosmis1 小时前
agent各指标定义
android·java·开发语言