第一次播放声音时 AVAudioPlayer 的启动缓慢 [英] Slow start for AVAudioPlayer the first time a sound is played

查看:24
本文介绍了第一次播放声音时 AVAudioPlayer 的启动缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 iPhone 上的 AVAudioPlayer 播放(非常短——不到 2 秒)音频文件时消除启动延迟.

I'm trying to eliminate startup lag when playing a (very short -- less than 2 seconds) audio file via AVAudioPlayer on the iPhone.

一、代码:

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];

我还实现了 audioPlayerDidFinishPlaying 方法以在完成后释放 AVAudioPlayer.

I also implement the audioPlayerDidFinishPlaying method to release the AVAudioPlayer once I'm done.

我第一次播放音频时,延迟是显而易见的——至少 2 秒.但是,此后声音会立即播放.我怀疑罪魁祸首是 [NSData dataWithContentsOfMappedFile] 最初从闪存中读取很长时间,但后来读取速度很快.不过,我不确定如何测试.

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.

是这样吗?如果是这样,我是否应该预先缓存 NSData 对象并在内存不足的情况下积极清除它们?

Is that the case? If so, should I just pre-cache the NSData objects and be aggressive about clearing them in low memory conditions?

推荐答案

延迟似乎与第一次实例化 AVAudioPlayer 有关.如果我加载任何音频,运行 [audioPlayer prepareToPlay] 然后立即释放它,我所有其他音频的加载时间都非常接近不可察觉.所以现在我在 applicationDidFinishLaunching 中这样做,其他一切都运行良好.

The delay seems to be related to instantiating AVAudioPlayer for the first time. If I load any audio, run [audioPlayer prepareToPlay] and then immediately release it, the load times for all of my other audio is very close to imperceptible. So now I'm doing that in applicationDidFinishLaunching and everything else runs well.

我在文档中找不到任何关于此的信息,但似乎确实如此.

I can't find anything about this in the docs, but it certainly seems to be the case.

这篇关于第一次播放声音时 AVAudioPlayer 的启动缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆