SoFunction
Updated on 2025-04-14

Audio Services and Audio AVAudioPlayer Audio Player Guide in iOS

AudioServicesPlaySystemSound Audio Service
For simple, no mix audio, the AVAudio ToolBox framework provides a simple C-style audio service. You can use the AudioservicesPlaySystemSound function to play simple sounds. The following rules must be followed:
1. The audio length is less than 30 seconds
2. The format can only be PCM or IMA4
3. The file must be stored in .caf, .aif, or .wav format
4. Simple audio cannot be played from memory, but only disk files
In addition to the restrictions on simple audio, you have basically no control over how audio playback is. Once the audio playback starts immediately, and it is the volume playback set by the current phone user. You will not be able to loop the sound and you will not be able to control the stereo effect. However, you can still set a callback function that is called when the audio playback is over, so you can clean up the audio objects and notify your program that the playback is over.
Directly upload the code:

Copy the codeThe code is as follows:

#import <AudioToolbox/> 
#import <CoreFoundation/> 
//This function will be called when the audio is played.
static void SoundFinished(SystemSoundID soundID,void* sample){ 
/*The playback is all over, so all resources are released */
    AudioServicesDisposeSystemSoundID(sample); 
    CFRelease(sample); 
    CFRunLoopStop(CFRunLoopGetCurrent()); 

//Main loop
int main(){ 
/*System audio ID, used to register the sound we will play*/
    SystemSoundID soundID; 
    NSURL* sample = [[NSURL alloc]initWithString:@""]; 
     
    OSStatus err = AudioServicesCreateSystemSoundID(sample, &soundID); 
    if (err) { 
        NSLog(@"Error occurred assigning system sound!"); 
        return -1; 
    } 
/*Add callback at the end of audio*/
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, SoundFinished,sample); 
/*Start playback*/
    AudioServicesPlaySystemSound(soundID); 
    CFRunLoopRun(); 
    return 0; 


I personally think this audio service is a bit useless, but it must have its place to use it. For example, if we want to play a custom warning sound or message prompt, using audio service will definitely save resources than other methods.

AVAudioPlayer Audio Player
There are three ways to play audio in IOS: AVAudioPlayer, audio service, and audio queue.
AVAudioPlayer is under the AVFoundation framework, so we need to import it.
The AVAudioPlayer class encapsulates the ability to play a single sound. The player can be initialized with NSURL or NSData. It should be noted that NSURL cannot be a network URL but must be a local file URL, because AVAudioPlayer does not have the ability to play network audio, but we can use a little trick to make it have this ability, and let it be explained later.
An AVAudioPlayer can only play one audio, if you want to mix it you can create multiple AVAudioPlayer instances, each equivalent to a track on the mixing board.
1. Create a player

Copy the codeThe code is as follows:

#import <AVFoundation/>    
NSError* err; 
AVAudioPlayer* player = [[AVAudioPlayer alloc] 
                        initWithContentsOfURL:[NSURL fileURLWithPath: 
                                              [[NSBundle mainBundle]pathForResource: 
                                           @"music" ofType:@"m4a"  
                                           inDirectory:@"/"]] 
error:&err ];//Create using local URL

Copy the codeThe code is as follows:

AVAudioPlayer* player = [[AVAudioPlayer alloc] 
                            initWithData:myData  
error:&err ];//Create using NSData
                           
I have said before that AVAudioPlayer cannot play network URLs, but can play NSData. We seem to be a little inspired. We can create NSData through network URLs, and then play NSData through AVAudioPlayer. Is it possible to play online music? However, this method is not advisable, because AVAudioPlayer can only play a complete file and does not support streaming, so it must be buffered before it can be played. So if the network file is too large or the network speed is not enough, wouldn’t it take a long time to wait? Therefore, we usually use an audio queue to play network audio.
2. Player properties
After creating an AVAudioPlayer, you can access or set its various properties.
1. Volume
Copy the codeThe code is as follows:

=0.8;//between 0.0~1.0

2. Number of cycles
Copy the codeThe code is as follows:

= 3;//Default is only played once.

3. Play location
Copy the codeThe code is as follows:

= 15.0;//You can specify to start playing from any location.

4. Number of channels
Copy the codeThe code is as follows:

NSUInteger channels = ;//Read-only attributes

5. Duration
Copy the codeThe code is as follows:

NSTimeInterval duration = ;//Get the duration of the sampling

6. Instrument counting
Copy the codeThe code is as follows:

= YES;//Open the instrument counting function
[ player updateMeters ];//Update the instrument reading
//Read the average level and peak level of each channel, representing the decibel number of each channel, with a range of between -100 and 0.
for(int i = 0; i<;i++){ 
float power = [player averagePowerForChannel:i]; 
float peak = [player peakPowerForChannel:i]; 


3. Play sound
After preparing for so long, I finally got to play. I was so excited.
Copy the codeThe code is as follows:

[ player prepareToPlay];//Assign the resources required for playback and add them to the internal playback queue.
[player play];//Play
[player stop];//Stop

Do you think it's over after preparing for so long? It's too fast, don't worry, there are a few more points.
IV. Agent method
If there is an exception when the playback is added, or it is interrupted by a higher-level system task, our program has ceased before it has time to end. What should we do? No hurry, we can handle all situations well through several delegation methods.
First, it is necessary to set a delegation to the player:
Copy the codeThe code is as follows:

= self; 

Copy the codeThe code is as follows:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{ 
//The action executed at the end of playback

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{ 
//The action executed by decoding error

- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{ 
//Code for processing interrupts

- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{ 
//Code processing the code that ends the interrupt


With this in mind, you can try to make a local player.