0

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

这是代码:

视图控制器.h

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

@interface STViewController : UIViewController

- (IBAction)playAudio:(id)sender;

@property (nonatomic, strong) NSArray *sounds;

@end

视图控制器.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;
}

但我不确定如何使其随机化,甚至在我现在正在使用的代码中实现。有人有想法么?

4

1 回答 1

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];
  }
于 2013-10-15T01:06:09.730 回答