Reputation: 103
I'm building an SongApp with random Sounds playing out of my Playlist.
I have now an NSMutableArray which contains Songs. For Example:
NSMutableArray *array=[NSMutableArray
arrayWithObjects:
@"Song1.mp3",
@"Song2.mp3",
@"Song3.mp3",
@"Song4.mp3",
@"Song5.mp3",
@"Song6.mp3",
@"Song7.mp3",
@"Song8.mp3",
@"Song9.mp3",
nil];
int i=0;
for(i=0;i<=[array count]; i++)
{
NSInteger rand=(arc4random() %9);
[array exchangeObjectAtIndex:i
withObjectAtIndex:rand];
}
I declared it as Instance Method.
Now i have many Buttons in different Colors. And each Button should play a Song. But everytime i call the new View, the Button should play an other Song.
I hope you understand me :)
My problem is:
Is there any way, that when i want, that the yellow button for example plays "Song1" overtime in this View, but when i load the View another time it plays "Song5" for example?
How can i say each Button to play out of my Array? I only know the
NSString *play = [[NSBundle mainBundle]
pathForResource:@"Song1" ofType:@"mp3"];
NSURL *playURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)playURL, & self.song1);
AudioServicesPlaySystemSound(self.song1);
Hope you understand my questions :)
Thanks & best regards!
Upvotes: 2
Views: 125
Reputation: 4065
One solution is to use this code to generate random number in the range of your array:
int max =5;
int min =1;
int randNum = rand() % (max - min) + min;
Then you can use [array objectAtIndex:randNum]
to access the song.
In your example:
NSString *play = [[NSBundle mainBundle]pathForResource:[array objectAtIndex:randNum] ofType:@"mp3"];
Upvotes: 0
Reputation: 1822
At first add to your project category for NSMutableArray(shuffle). There are many different variants in internet. For Example: https://stackoverflow.com/a/56656/1401067 http://nazcalabs.com/blog/how-to-shuffle-a-nsmutablearray-objective-c/
Then add this code in your controller. Or to another initialization place.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.sondsArray shuffle];
}
After that set different tags to all buttons. From 100(For example) to (100-1+self.sondsArray).
And the last step is buttons pressed action handling. So:
- (IBAction)songButtonPressed:(UIButton *)button
{
[self playSongWithName:sondsArray[button.tag-100]];
}
So. Good luck in you code =)
Upvotes: -1
Reputation: 3733
if you used arc4random()
. then it will pickup random index from your array. that you are not predict. if you want the random function will work according to your requirement the you need to do manual coding for same according to your requirement.
Hope this help you.
Upvotes: 1
Reputation: 104
You can use the MPMediaPickerController class and implement it's methods to get songs from one's iPod Library.
If you have already have the files embedded in your application, simply pass the object at index to the Audio Services, while generating a random index each time.
Upvotes: 1