Category Archives: iOS

Fixed: AVAudioPlayer Only Play 1-2s in iOS 6

I am developing Coco Voice ( http://cocovoice.com/ ) these days. After updating to iOS 6, no matter iOS 6 beta 4, iOS GM or iOS 6.0 release, I found that AAC-encoded voice message could not be played correctly. Only 1~2 seconds of voice was played even though the message was far longer than 2 seconds. But if I set currentTime to >= 1.4s, it will play the whole message after the given currentTime value. In this case, we always lose the first seconds message. Unacceptable for a voice mobile IM.

Searching the web, it seems only a few guys met with this problem. Someone explained that the duration is incorrect for AAC-encoded voice data. And some of them said they have reported this bug to Apple already (but I could not find the bug report). iOS 6.0 was just released yesterday or so, it may take at least a month or so for iOS 6.0.1 for this bug-fix. So we won’t just wait.

After lots of try, here is the solution:

AVAudioPlayer *soundPlayer = [[AVAudioPlayer alloc] initWithData:message error:&err];
soundPlayer.volume = 1.0f;
soundPlayer.currentTime = soundPlayer.duration + soundPlayer.duration;
soundPlayer.numberOfLoops = 1;
[soundPlayer setDelegate:self];
[soundPlayer prepareToPlay];
[soundPlayer play];

Just set currentTime to the end of the message and tell player to play the message twice. So it will be correctly played once. And set double duration to currentTime will make sure that player does not play the end of message twice.

BTW: If you set currentTime to 1.4f, and then NSLog the currentTime, you will find out that it will be changed to a different value.

Posted in iOS, Objective-C | 2 Comments