1

So as I'm writing this, I'm realizing just how specific this issue is...

I'm making an iOS app which plays sounds over other apps' music, but with some apps (so far only one, actually), I'm experiencing a lag when playing sounds that doesn't occur when this app isn't playing its music, i.e.

  1. Start playback using the Soundcloud app
  2. Load my app
  3. Press button to play sound
  4. Sound plays

If I omit step 1 (or use a different app, see below), there is no (perceivable) delay between 3 & 4, but keeping step 1 there, I hear a small (~200ms) delay in the playback start.

I have tried using AVAudioPlayer using [player prepareToPlay]:

- (void)prepPlayer:(Sound *)sound
{
  NSURL* pathURL = [NSURL fileURLWithPath:[sound getStoragePath] isDirectory:NO];
  AVAudioPlayer* newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:&error];
  [newPlayer prepareToPlay];
}

- (void)playSound
{
  player.currentTime = 0;
  [player play];
}

and AVAudioPlayerNode / AVAudioEngine / AVAudioMixerNode using:

- (void)prepQuickSound:(Sound *)sound
{
  self.audioEngine = [[AVAudioEngine alloc] init];
  self.audioMixerNode = [[AVAudioMixerNode alloc] init];

  [self.audioEngine attachNode:self.audioMixerNode];
  [self.audioEngine connect:self.audioMixerNode to:self.audioEngine.outputNode format:nil];

  self.player = [[AVAudioPlayerNode alloc] init];
  [audioEngine attachNode:playerNode];
  [audioEngine connect:playerNode to:mixerNode format:nil];

  NSURL* pathURL = [NSURL fileURLWithPath:[sound getStoragePath] isDirectory:NO];
  NSError *audioLoadError = nil;  
  self.quickAudioFile = [[AVAudioFile alloc] initForReading:pathURL error:&audioLoadError];
}

- (void)playQuickSound
{
  [self.player stop];
  [self.player scheduleFile:self.quickAudioFile atTime:nil completionHandler:nil];
  [self.player play];
}

...but I see the same delay regardless.

This delay doesn't happen when playing music using the Music (iTunes) app, or Spotify, so I guess it's something that the SoundCloud app is doing in particular, but I'm wondering if there's a way I can get around it.

I'm really hoping someone here has had a similar issue and solved it - I can't find anything from my google searches...

head in the codes
  • 1,159
  • 12
  • 24
  • 1
    Have you considered claiming the audio session before starting to play audio in your app? – Adeel Miraj Sep 09 '21 at 08:13
  • I have, but the only category that fits my need is `AVAudioSessionCategoryAmbient` (I want to play over other apps), and after trying all legal/valid settings of `mode`, `routeSharingPolicy` and `options` I still get the delay – head in the codes Sep 15 '21 at 03:28

0 Answers0