Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

neil.b

macrumors member
Original poster
Nov 20, 2008
65
0
(I posted this on the Apple Developer Forums, cross-posting here in case anyone finds it useful)

Some information for people who, like me, were sometimes struggling to get acceptable results when trying to use AVAudioPlayer to play looping sounds.

Don't use a compressed format or you'll get unpredictable results.

The reason for this is in the way compressed audio is stored compared to uncompressed audio. Lets say, for example, you have an uncompressed sound file which is 23600 samples long and you save the file as a .CAF file which is compressed using AAC which, for simplicity, is compressed at a ratio of 4:1. Ignoring the file header and (again) for the sake of simplicity, the data in the file is stored in blocks of 1024 samples. 23600 samples compressed @ 4:1 equals 5900 samples, so you might expect your file would look like this;

block 0 : 1024 samples
block 1 : 1024 samples
block 2 : 1024 samples
block 3 : 1024 samples
block 4 : 1024 samples
block 5 : 780 samples

As you can see though, because the actual length of the sound file is not an exact multiple of 1024 samples, the last block only contains 780 samples. Because variable block lengths are not allowed (not in any compressed format I know but I could be wrong - it's certainly true of MP3/AAC) the encoder has to deal with that last block by padding out the end with silence. Therefore in the actual AAC file you'll have;

block 0 : 1024 samples
block 1 : 1024 samples
block 2 : 1024 samples
block 3 : 1024 samples
block 4 : 1024 samples
block 5 : 780 samples + 244 samples of silence/0

This is fine for non looping sounds but the problem is obvious if you attempt to play this expecting a seamless loop. Your sound file should loop at the 5900th sample but because this would be in the middle of a block of 1024 samples, looping doesn't actually occur until 244 samples later, hence you get a small pause or glitch at the loop point.
 
I registered on this forum in order to post this and thank you for this thread.

You solution worked like a charm, when everything else I had tried, simply failed miserably.

I was actually using an AVPlayer to loop an .MP4 video file and never crossed my mind that the compression of the audio to MP3/AAC could cause this problem. So, I switched the format to .MOV which allows the audio to stay uncompressed, and the sound glitch at the loop transition disappeared!

Fantastic! Can't thank you enough for sharing this.
 
I recognize this is a very old post, but a big Thank You! for explaining this.

I worked around my particular issue by using a very long pre-looped, compressed m4a file. My file is long enough that no one should ever notice it loop.

(Cannot believe this is still an issue after 4 years.)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.