C# – 播放文件夹中的随机声音文件
我正在尝试创建一个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 ),但我不知道如何在我给定的场景中实现它。
如果你有一个特定的文件夹,你可以做这样的事情;
var soundsRoot = @"c:\lyde"; var rand = new Random(); var soundFiles = Directory.GetFiles(sounds, "*.wav"); var playSound = soundFiles[rand.Next(0, soundFiles.Length)]; System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(playSound);
// List of files from directory, sorted by *.wav type. string[] filePaths = Directory.GetFiles(@"F:\Tankat\Music", "*.wav", SearchOption.AllDirectories); // Random number from 0 to the amount of files you have Random rnd = new Random(Guid.NewGuid().GetHashCode()); int choices = rnd.Next(filePaths.Length); // Create a new player with a random filepath from the array SoundPlayer player = new SoundPlayer(filePaths[choices]); player.Play();
从文件夹中检索声音文件列表,然后选择0和list.Length-1之间的随机数并选择该文件。
//Untested code, but should give you an idea. string[] files = Directory.GetFiles("path"); Random rnd = new Random(Guid.NewGuid().GetHashCode()); int choice = rnd.Next(0, files.Length - 1); string soundFile = files[choice]; System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundFile); player.Play();
试试这个
并改变线
string[] dirs = Directory.GetFiles(@"c:\", "c*");
至
string[] dirs = Directory.GetFiles(@"c:\Lyde\", "c:\Lyde\*.wav");
(未经测试)
然后你应该有一个包含所有.wav文件的数组。