I have one thousand .mp3
files in my Resources
folder within an iOS 4.2 XCode project.
For now I can select one file from the folder ( and play it ) with the following code in my .m
file: ( Given the file name of "AFile.mp3" )
-(IBAction)playSound {
NSString *path = [[NSBundle mainBundle] pathForResource:@"AFile"ofType:@"mp3"];
AVAudioPLayer* theAudio =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
I'd like to be able to have the code choose an .mp3
randomly, play it, then select another file and play them all until they have all been played at least once. I assume I will need to use an NSArray, but am uncertain on how to proceeed.
I changed the code to the following, and am not getting any errors when I run this in the iOS Simulator. No File appears to be played when I run it though? When I launch the app, it quits, but does not log any errors in the Debugger..
Updated code:
-(IBAction)playSound {
NSArray *array = [[NSBundle mainBundle] pathsForResourcesOfType:@".mp3" inDirectory:@"Resources"];
NSString *randomPath = [array objectAtIndex:arc4random() % [array count]];
AVAudioPlayer* theAudio =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: randomPath] error: NULL;
theAudio.delegate = self;
[theAudio play];
}
How can an I set up a simple array of the 1000 .mp3
files, and have the method play one at random?