Skip to main content
 首页 » 编程设计

C#之从文件夹中播放随机声音文件

2024年02月13日18zhenyulu

<分区>

我正在尝试创建一个 Oracle(阅读:Magic 8 Ball)。 其背后的想法是,在每次按下按钮时,都会播放一个带有明智话语的声音文件(随机选择)。 我使用开关让它工作,但是我正在寻找一种方法让它更……合乎逻辑。

这是它当前的样子,开关不断打开:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
 
namespace _8ball 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
 
        private void button1_Click(object sender, EventArgs e) 
        { 
            Random rnd = new Random(Guid.NewGuid().GetHashCode()); 
            int choices = rnd.Next(0, 62); 
            switch(choices) 
            {  
                case 0: 
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\Lyde\0.wav"); 
                    player.Play(); 
                    break; 
                case 1: 
                    System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(@"c:\Lyde\1.wav"); 
                    player1.Play(); 
                    break; 
                case 2: 
                    System.Media.SoundPlayer player2 = new System.Media.SoundPlayer(@"c:\Lyde\2.wav"); 
                    player2.Play(); 
                    break; 
                case 3: 
                    System.Media.SoundPlayer player3 = new System.Media.SoundPlayer(@"c:\Lyde\3.wav"); 
                    player3.Play(); 
                    break; 

当然有一种方法可以对其进行编程,使其在给定的文件夹中查找,然后选择一个随机文件,而无需在程序本身中说明该文件(就像它是如何使用开关完成的)。 我偶然发现了文件夹枚举 ( http://code.msdn.microsoft.com/windowsapps/Folder-enumeration-sample-33ebd000 ),但我不确定如何在我给定的场景中实现它。