Skip to main content
 首页 » 编程设计

c#之播放随机 mp3 文件未知错误

2024年02月24日25xing901022

这在我只调用该函数并播放文件时有效,但是如果我想从文件夹中选择一个随机 mp3 来播放,它会停止说“索引超出数组范围”。

任何人都可以找出问题所在吗?

public void playrandomsound() 
    { 
        if (mp3 != null) 
        { 
            mp3.Dispose(); 
        } 
 
        var files = new DirectoryInfo(Application.StartupPath).GetFiles(".mp3"); 
        int index = new Random().Next(0, files.Length); 
 
 
        string filename = files[index].Name.ToString();      <-- App stops here 
 
        string tune = string.Concat(Application.StartupPath, "//", fiilename); 
        mp3 = new Audio(tune); 
        mp3.Play(); 
 
 
 
    } 

如果我删除错误行上的“tostring”方法,它仍然会给出相同的错误。

请您参考如下方法:

正如 Skurmedel 所说,您需要防止出现空集合。但是,您遇到此问题的原因是您的收藏中永远没有任何 .mp3 文件。另一个错误在这里:.GetFiles(".mp3")。你的意思是 .GetFiles("*.mp3")。