I'm trying to eliminate startup lag when playing a (very short -- less than 2 seconds) audio file via AVAudioPlayer on the iPhone.
First, the code:
NSString *audioFile = [NSString stringWithFormat:@"%@/%@.caf", [[NSBundle mainBundle] resourcePath], @"audiofile"];
NSData *audioData = [NSData dataWithContentsOfMappedFile:audioFile];
NSError *err;
AVAudioPlayer *audioPlayer = [(AVAudioPlayer*)[AVAudioPlayer alloc] initWithData:audioData error:&err];
audioPlayer.delegate = self;
[audioPlayer play];
I also implement the audioPlayerDidFinishPlaying method to release the AVAudioPlayer once I'm done.
The first time I play the audio the lag is palpable -- at least 2 seconds. However, after that the sound plays immediately. I suspect that the culprit, then, is the [NSData dataWithContentsOfMappedFile] taking a long time reading from the flash initially, but then being fast on later reads. I'm not sure how to test that, though.
Is that the case? If so, should I just pre-cache the NSData objects and be aggressive about clearing them in low memory conditions?
question from:
https://stackoverflow.com/questions/900461/slow-start-for-avaudioplayer-the-first-time-a-sound-is-played 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…