Playing Random Sounds

Discussion in 'iOS Programming' started by Ryan Burgess, Jul 27, 2013.

  1. Ryan Burgess macrumors 6502

    Jan 26, 2013
    Hi, I am trying to make an app where pressing a button will play a random sound. I have the code written and am getting no errors, however the sounds don't play on my iPhone that I'm testing it with.

    I've connected the button to the IBAction I want it to perform, but when it's tapped I get nothing.

    Here is my Main.m code

    #import "ViewController.h"
    @interface ViewController ()
    @implementation ViewController
    - (AVAudioPlayer *)setupAudioPlayerWithFile:(NSString *)file type:(NSString *)type
        NSString *path = [[NSBundle mainBundle] pathForResource:file ofType:type];
        NSURL *url = [NSURL fileURLWithPath:path];
        NSError *error;
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        if (!audioPlayer) {
            NSLog(@"%@",[error description]);
        return audioPlayer;
    - (void)viewDidLoad
        [super viewDidLoad];
    - (void)didReceiveMemoryWarning
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
        int randomNumber = arc4random() % 68 + 1;
        NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound %02d", randomNumber] ofType:@"wav"]];
        AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
        [soundPlayer setVolume:0.3];
        [soundPlayer prepareToPlay];
        [soundPlayer play];
    My audio files are named like this "Sound 01.wav" if anyone can see my error, please point it out! Thanks!
  2. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia
    You show a method setupAudioPlayerWithFile and then never use it. Delete it if it isn't used.

    Then, your IBAction method has a big complex line that does everything at once. You can't debug that.

    Break that line into 3 or 4 lines:

    Build the string.
    Get the path from the bundle
    Use the path to create a URL
    Initialize the audio player using the URL.

    Then step through that code in the debugger. Examine the results of each step. At some point you'll see a result you don't expect, and that will be the cause of your problem.

    My bet is that you forgot to add the sound files to your project, or their target membership checkbox is not checked, so they are not getting copied into your app's bundle.

    NSBundle methods return nil if they can't find the file you are asking for. I bet you're getting nil back from the call to pathForResource:eek:fType: .


Share This Page