如何制作具有客观c的随机声音阵列?

时间:2013-10-15 00:36:59

标签: objective-c

所以我已经完成了编写按钮的教程,这样当你按下它时会播放声音。我正在尝试对其进行修改,以便在按下按钮时播放随机声音。

这是代码:

viewcontroller.h

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>

@interface STViewController : UIViewController

- (IBAction)playAudio:(id)sender;

@property (nonatomic, strong) NSArray *sounds;

@end

viewcontroller.m

#import <AVFoundation/AVFoundation.h>
#import "STViewController.h"

@interface STViewController ()

@property (weak, nonatomic) IBOutlet UIButton *playAudio;

@end

@implementation STViewController


- (IBAction)playAudio:(id)sender {
    AVAudioPlayer *audioPlayer;
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"Woof" ofType:@"mp3"];
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    NSError *audioError = [[NSError alloc] init];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&audioError];

    if (!audioError) {
        [audioPlayer play];
        NSLog(@"Woof!");
    }
    else {
        NSLog(@"Error!");
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

我一直在涉足这些方面的事情

- (NSArray *)sounds
{
    NSArray *sounds = [NSArray arrayWithObjects:
                       @"Woof.mp3",
                       @"Meow.mp3",
                       @"tweet.mp3",
                       @"Squeak.mp3",
                       @"Moo.mp3",
                       @"Croak.mp3",
                       @"Toot.mp3",
                       @"Quack.mp3",
                       @"Blub.mp3",
                       @"OWOwOw.mp3",
                       @"Fox.mp3",
                       nil];

    return sounds;
}

但是我不确定如何使它随机或甚至在我现在的代码中实现。有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

只需随意尝试下面: -

      NSMutableArray *array=[NSMutableArray     
       arrayWithObjects:
                   @"Woof.mp3",
                   @"Meow.mp3",
                   @"tweet.mp3",
                   @"Squeak.mp3",
                   @"Moo.mp3",
                   @"Croak.mp3",
                   @"Toot.mp3",
                   @"Quack.mp3",
                   @"Blub.mp3",
                   @"OWOwOw.mp3",
                   @"Fox.mp3",
                   nil];

           // now use exchangeobject with index api
          int i=0;
      for(i=0;i<=[array count]; i++)
     {

   NSInteger rand=(arc4random() %10);
  [array exchangeObjectAtIndex:i    
  withObjectAtIndex:rand];
  }