Giel
Giel

Reputation: 311

Play a random sound

How can i play a random sound in iOS 5 in xcode? I keep getting a "throwing an exception" error.

I tried this:

int randomNumber = arc4random() % 24 + 1;

NSString *tmpFileNameRandom = [[NSString alloc] initWithFormat:@"Sound%d", randomNumber];

NSString *fileName = [[NSBundle mainBundle] pathForResource:tmpFileNameRandom ofType:@"mp3"];

AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName] error:nil];

[soundPlayer prepareToPlay];
[soundPlayer play];

Thank you!

Upvotes: 2

Views: 1977

Answers (3)

Rok Jarc
Rok Jarc

Reputation: 18875

First, change your ViewController.h to

#import <UIKit/UIKit.h>

@class AVAudioPlayer;

@interface ViewController : UIViewController

-(IBAction)PlayRandomSound;
@property (nonatomic, retain) AVAudioPlayer *soundPlayer;


@end

and first lines of ViewController.m to

#import "ViewController.h"

#import <AVFoundation/AVAudioPlayer.h>


@implementation ViewController

@synthesize soundPlayer = _soundPlayer;


-(IBAction)PlayRandomSound{

    int randomNumber = arc4random() % 8 + 1;

    NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];


    _soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];

    [_soundPlayer prepareToPlay];
    [_soundPlayer play];


    NSLog(@"randomNumber is %d", randomNumber);
    NSLog(@"tmpFilename is %@", soundURL);
}

Edit: i only later noticed that you don't use ARC so this code has a small leak. But it will do for start. Maybe you should set _soundPlayer to nil when you create ViewController and later check: if it's not nil: release it and create new one, otherwise just create new one. Or you could consider switching to ARC if it's a new project.

Upvotes: 3

Rok Jarc
Rok Jarc

Reputation: 18875

For your filenames you should use

NSString *tmpFileNameRandom = [[NSString alloc] initWithFormat:@"Sound%02d", randomNumber];

this will give you leading zeros with numbers < 10...

or better yet, try this:

int randomNumber = arc4random() % 24 + 1;

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];

AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];

[soundPlayer prepareToPlay];
[soundPlayer play];

Upvotes: 1

Jodocus
Jodocus

Reputation: 151

Have you added the AVFoundation framework to your project? AVAudioPlayer is a class of this framework.

To add this framework (in Xcode 4), select your project file, select the 'Summary' tab and add it by clicking on the + below the "Linked frameworks and libraries" tableview.

Upvotes: 0

Related Questions