Quaso
Quaso

Reputation: 373

Playing wav sound file with AVFoundation

I am using AVFoundation to play wav files. But i could not make it play. Also no errors or warnings showed up.

XCode is 4.2 and device is iOS 5.

- (IBAction) playSelectedAlarm:(id)sender {

UIButton *button = (UIButton *)sender;

int bTag = button.tag;

NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];

NSLog(@"%@", fileName);

NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

AVAudioPlayer *theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];

theAudio.volume = 1.0;

theAudio.delegate = self;

[theAudio prepareToPlay];

[theAudio play];

}

Upvotes: 3

Views: 12860

Answers (2)

bndouglas
bndouglas

Reputation: 135

I have had the same issue with Xcode 4.5. Making the AVAudioPlayer into a strongly typed property made it play.

So the following code needs added to the @interface:

@property (nonatomic, strong) AVAudioPlayer *theAudio;

The @implementation would then become:

- (IBAction) playSelectedAlarm:(id)sender {

    UIButton *button = (UIButton *)sender;

    int bTag = button.tag;

    NSString *fileName = [NSString stringWithFormat:@"%d23333", bTag];

    NSLog(@"%@", fileName);

    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

    self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];

    self.theAudio.volume = 1.0;

    self.theAudio.delegate = self;

    [self.theAudio prepareToPlay];

    [self.theAudio play];

}

Upvotes: 4

Quaso
Quaso

Reputation: 373

Here is the solution;

I set AVAudioPlayer in header file..

@property (nonatomic, retain) AVAudioPlayer *theAudio;

i guess 'retain' is solved my problem. Because after i sending "play", it sends "release" to balance the alloc. When AVAudioPlayer is deallocated it stops playing audio.

Upvotes: 5

Related Questions