iOS Objective C像SoundPool一样的低延迟音频播放

iOS Objective C像SoundPool一样的低延迟音频播放

问题描述:

在我的Android应用程序中嗨,我可以在SoundPool中预载我的声音,然后几乎没有延迟地播放它们。现在我在iOS/obj-c上寻找同样的东西,但我找不到任何类似的东西。iOS Objective C像SoundPool一样的低延迟音频播放

我跟着几个教程,但最终有一个比我预期的更大的滞后和大多数教程建议您将音频转换为像wav或caf这样的未压缩格式,但我的MP3已经在14 MB并转换他们无损音频导致81 MB的数据,这对我来说太多了。

我试过了预加载文件(就像我在Android的的Soundpool所做的那样)像显示在此OAL例如最有前途的事情:

- (bool) preloadUrl:(NSURL*) url seekTime:(NSTimeInterval)seekTime 
{ 
    if(nil == url) 
    { 
     OAL_LOG_ERROR(@"%@: Cannot open NULL file/url", self); 
     return NO; 
    } 

    OPTIONALLY_SYNCHRONIZED(self) 
    { 
     // Bug: No longer re-using AVAudioPlayer because of bugs when using multiple players. 
     // Playing two tracks, then stopping one and starting it again will cause prepareToPlay to fail. 

     bool wasPlaying = playing; 

     [self stopActions]; 

     if(playing || paused) 
     { 
      [player stop]; 
     } 

     as_release(player); 

     if(wasPlaying) 
     { 
      [[NSNotificationCenter defaultCenter] performSelectorOnMainThread:@selector(postNotification:) withObject:[NSNotification notificationWithName:OALAudioTrackStoppedPlayingNotification object:self] waitUntilDone:NO]; 
     } 

     NSError* error; 
     player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
     if(nil == player) 
     { 
      OAL_LOG_ERROR(@"%@: Could not load URL %@: %@", self, url, [error localizedDescription]); 
      return NO; 
     } 

     player.volume = muted ? 0 : gain; 
     player.numberOfLoops = numberOfLoops; 
     player.meteringEnabled = meteringEnabled; 
     player.delegate = self; 
     player.pan = pan; 

     as_release(currentlyLoadedUrl); 
     currentlyLoadedUrl = as_retain(url); 

     self.currentTime = seekTime; 
     playing = NO; 
     paused = NO; 

     BOOL allOK = [player prepareToPlay]; 
     if(!allOK) 
     { 
      OAL_LOG_ERROR(@"%@: Failed to prepareToPlay: %@", self, url); 
     } 
     else 
     { 
      [[NSNotificationCenter defaultCenter] performSelectorOnMainThread:@selector(postNotification:) withObject:[NSNotification notificationWithName:OALAudioTrackSourceChangedNotification object:self] waitUntilDone:NO]; 
     } 
     preloaded = allOK; 
     return allOK; 
    } 
} 

但是,这仍然使大约〜60ms的一个相当大的延时,对于像我这样的音频应用来说太过分了。我的音频文件在开始时没有任何延迟,因此它必须对代码进行一些操作。

我尝试了iPhone 5c上的所有东西。

应该能够创建多个AVAudioPlayer S和呼吁他们prepareToPlay,但我个人喜欢用AVAssetReader保持LPCM的缓冲音频准备在片刻的通知玩。

+0

好的,打算创建200个播放AVAudioPlayers然后大声笑我会告诉你它是怎么回事 – user2875404 2015-04-05 21:37:19

+0

好的队友非常感谢,把他们放在一个数组中,使得这个工作比我想的要复杂得多成为;这是现在完美的工作! – user2875404 2015-04-05 22:02:21