Technology Sharing

Playing AAC using Audio Services in Audio Toolbox

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Playing AAC using Audio Services in Audio Toolbox

Playing AAC using Audio Services in Audio Toolbox

It is mainly divided into 3 steps:

  1. use AudioServicesCreateSystemSoundID Create system sounds.
  2. use AudioServicesAddSystemSoundCompletion Set callback.
  3. use AudioServicesPlaySystemSound Start playing.

about AudioServicesPlaySystemSound function:

This function plays a short sound (duration 30 seconds or less). Because a sound may play for several seconds, this function executes asynchronously. To find out when the sound has finished playing, call AudioServicesAddSystemSoundCompletion Function to register callback function.

On some iOS devices, you can AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) To invoke vibration. On other iOS devices, calling this function with this constant has no effect.

The following are the restrictions on the audio files that this function can play:

  • No longer than 30 seconds in duration
  • In linear PCM or IMA4 (IMA/ADPCM) format
  • Packaged in a .caf, .aif, or .wav file

But in fact, AAC files can also be played normally. In addition, this function has many limitations:

  • Sounds play at the current system audio volume, with no programmatic volume control.
  • The sound plays immediately.
  • Looping and stereo positioning are not supported.
  • Cannot play simultaneously, only one sound can play at a time.
  • Sound plays locally on the device speakers and does not use audio routing.

Core code:

- (void)btnClick:(UIButton *)sender
{
    self.mButton.hidden = YES;
    NSURL *audioUrl = [[NSBundle mainBundle] URLForResource:@"music" withExtension:@"aac"];
    SystemSoundID soundID;
    // create a system sound object
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioUrl, &soundID);
    // register a callback function that is invoked when a specified system sound finishes playing
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, &playCallback, (__bridge void *_Nullable)(self));
    // play a system sound object
    AudioServicesPlaySystemSound(soundID);
}

void playCallback(SystemSoundID ssID, void  *clientData)
{
    ViewController *vc = (__bridge ViewController *)clientData;
    vc->_mButton.hidden = NO;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Project address: https://github.com/UestcXiye/AudioToolboxSystemSound.