我试图通过iPhone上的AVAudioPlayer播放(非常短 - 少于2秒)的音频文件来消除启动延迟.
一,代码:
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];
Run Code Online (Sandbox Code Playgroud)
一旦完成,我还实现了audioPlayerDidFinishPlaying方法来释放AVAudioPlayer.
我第一次播放音频时滞后是显而易见的 - 至少2秒.然而,之后立即播放声音.我怀疑那个罪魁祸首是[NSData dataWithContentsOfMappedFile]最初从闪存中读取了很长时间,但后来读取速度很快.不过,我不确定如何测试.
是这样的吗?如果是这样,我是否应该预先缓存NSData对象并积极地在低内存条件下清除它们?
我正在使用SKTAudioRay Wenderlich在他的Github上提供的库.这是我为播放声音效果而修改的代码,我每次播放时都会调用它:
public func playSoundEffect(_ filename: String) {
let url = Bundle.main.url(forResource: filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}
if !UserDefaults.standard.bool(forKey: "soundOff"){
var error: NSError? = nil
do {
soundEffectPlayer = try AVAudioPlayer(contentsOf: url!)
} catch let error1 as NSError {
error = error1
soundEffectPlayer = nil
}
if let player = soundEffectPlayer {
DispatchQueue.global(qos: .background).async {
player.numberOfLoops = 0
player.prepareToPlay()
player.play()
}
} else {
print("Could not create audio …Run Code Online (Sandbox Code Playgroud) -(IBAction)playSound{ AVAudioPlayer *myExampleSound;
NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"myaudiofile" ofType:@"caf"];
myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:NULL];
myExampleSound.delegate = self;
[myExampleSound play];
}
Run Code Online (Sandbox Code Playgroud)
我想在点击按钮时发出哔哔声.我使用了上面的代码.但播放声音需要一些延迟.
有人请帮忙.
iphone ×2
audio ×1
caching ×1
cocoa-touch ×1
ios ×1
nsdata ×1
objective-c ×1
sprite-kit ×1
swift ×1
xcode ×1