Alex Rivera | Logout

MP3 playing using AVAudioPlayer not working on device

Asked 2011-01-09T18:20:59.720
19

I am testing my app on my 3GS iPhone with iOS 4.2

I am using the following code which plays a sound in my IBAction. It works perfectly in the simulator (both iPad and iPhone) - I hear the sound.

NSString *pathToMusicFile1 = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"mp3"];
NSError *error;
alarmSound = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile1] error:&error]; 
NSLog(@"Song1 Loaded");
if (alarmSound == nil) {
    NSLog(@"Error playing sound");
} else {
    alarmSound.numberOfLoops = 20;
    alarmSound.volume = 1.0;
    [alarmSound play];
}

I have everything declared properly (headers and frameworks etc) as I can hear the sound in the simulator.

I have also checked that my phone is NOT in silent mode!! I hear other sounds from the generic iphone GUI. (example from a datepicker).

I have also cleaned all targets and deleted the app to reinstall.

Any ideas what's wrong?!

Edit
Report

2 Answers

17

My problem was that iOS was autoreleasing my AVAudioPlayer instance before the file got a chance to play. Strangely this only happened with MP3s and not AU files. Solution was to not set it as autorelease and then release it in the delegate method...

- (void)playSound:(NSString *)sound
{
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@""]] error:NULL];
    audioPlayer.delegate = self;
    [audioPlayer play];
}

...then in the delegate method...

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player release];
}

...works great now.

answered 2011-08-25T17:31:08.783
1

have you tried [NSURL URLWithString:pathToMusicFile1]; instead of fileURLWithPath:?

answered 2011-01-09T18:27:31.710

Your Answer