Shaitan00 Posted July 15, 2006 Posted July 15, 2006 I have a folder [souds\Backgrounds] full on Midi files which I can play using a function [PlayMidiFile(string MidiFile)] and everything works fine... Thing is this folder [souds\Backgrounds] has a large amount of Midi files (and some other non-music files that must be ignored) and I want my program to randomly choose one everytime it starts... So, essentially I want to pass into [PlayMidiFiles] a string (MidiFile) representing the filename (with path) of a randomly selected Midi file in the [souds\Backgrounds] folder... So far this is what I have, I am able to get a string[] with a list of all the possible midi files, but now how do I RANDOMLY select one? string sSelected = null; string[] sFileList = System.IO.Directory.GetFiles("Sounds\\Backgrounds", "*.mid"); // ... Randomly select one of the strings from sFileList[] and put it in sSelected ... // Play Selected File if (PlayMidiFile(sSelected) == 0) return true; else return false; So, I need to somehow fill the string variable "sSelected" with one of the random values in "sFileList" Any ideas, hints, and help would be greatly appreciated, thanks Quote
FunUsePro Posted July 16, 2006 Posted July 16, 2006 the simplest way to get a random item from an array is using the Random class, so like in your case, it would be something like this: string[] items = ...loaded items...; Random r = new Random(); int randomedIndex = r.Next(0, items.Length - 1); then u can just do whatever by getting the item that corresponds to that random number that was constrained to the array's length: string selected = ""; selected = items[randomedIndex]; Some people will tell you that .Net's Random class is very far from being random, but it is simple to implement. If you want a more random number generator then look around on google, there are quite a bit out there. Quote
Leaders snarfblam Posted July 16, 2006 Leaders Posted July 16, 2006 If it is true that the .Net Random class is not very "random," it hardly matters in the context of picking a random song. The only time this might ever be an issue is in some sort of scientific or mathematical application. Quote [sIGPIC]e[/sIGPIC]
Administrators PlausiblyDamp Posted July 16, 2006 Administrators Posted July 16, 2006 If you want to make sure each item is played once before duplicates then you could load the filenames into an array and then randomise the array, then just keep selecting the next item in the array. string[] items = ...loaded items...; Random r = new Random(); byte[] b = new byte[items.Length]; r.NextBytes(b); Array.Sort(b, items); Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.