-3

The code is suppose to make a sound either yes or yes 3 play when clicked, but I get an error before I begin to debug that says rand cannot be statically allocated, but I can't put a * there because it's an integer. I am getting a conversion error when I do that. I also tried putting a * before sound, and that solved the error issue but when the button is clicked it wont play anything. So what do I do?

#import "ViewController.h"
#import <AVFoundation/AVAudioPlayer.h>

@interface ViewController ()

@end

@implementation

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

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}//this is where the error breakpoint is that you show me how to make

- (IBAction)Yes {

    NSInteger rand = arc4random_uniform(2);

    NSString sound = rand == 0 ? @"yes" : @"yes 3";

    NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:@"mp3"];


    AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    [audioPlayer play];
}

@end
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
cloudhalo
  • 11
  • 5

1 Answers1

0

I've seen this many times before, and it has to do with the fact that your audio player variable is being released before it has a chance to play the file.

You need to create a property for the audio player in your header:

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

Then in your method access that property instead of the local variable:

- (IBAction)YES {
    NSInteger rand = arc4random_uniform(2);
    NSString *sound = rand == 0 ? @"yes" : @"yes 3";
    NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:@"mp3"];

    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [self.audioPlayer play];
}

Note that this has absolutely nothing to do with the sound variable you're messing with. You should be using the * to indicate a pointer when creating that variable, as shown above.

Mike
  • 9,765
  • 5
  • 34
  • 59