iOS Audio Service and Audio AVAudioPlayer Audio Player User guide

  • 2020-06-12 10:41:43
  • OfStack

AudioServicesPlaySystemSound Audio Service
For simple, remix-free audio, the AVAudio ToolBox framework provides a simple C language-style audio service. You can use the AudioservicesPlaySystemSound function to play simple sounds. Here are some rules to follow:
1. Audio length is less than 30 seconds
2. Format PCM or IMA4 only
3. The file must be stored in.caf,.aif, or.wav format
4. Simple audio cannot be played from memory, only from disk
In addition to restrictions on simple audio, you have little control over how the audio is played. Once the audio starts playing, it is played at the volume set by the current phone user. You won't be able to loop sound, nor will you be able to control stereo effects. However, you can set up a callback function to be called at the end of the audio playback so that you can clean up the audio object and notify your application that the playback is over.
Direct code:


#import <AudioToolbox/AudioToolbox.h> 
#import <CoreFoundation/CoreFoundation.h> 
// This function is called when the audio is finished playing  
static void SoundFinished(SystemSoundID soundID,void* sample){ 
    /* The playback is complete, so release all resources */ 
    AudioServicesDisposeSystemSoundID(sample); 
    CFRelease(sample); 
    CFRunLoopStop(CFRunLoopGetCurrent()); 

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


Personally, I think this audio service is a bit lame, but it certainly has its USES. For example, if we want to play a custom warning or message, the audio service will definitely save resources compared to other methods.

AVAudioPlayer audio player
There are three ways to play audio in IOS: AVAudioPlayer, Audio service, and audio queue.
AVAudioPlayer is under the FRAMEWORK of AVFoundation, so we need to import ES30en.framework.
The AVAudioPlayer class encapsulates the ability to play a single sound. The player can be initialized with NSURL or NSData. It's important to note that NSURL can't be network url, it has to be a local file, URL, because AVAudioPlayer doesn't have the ability to play network audio, but we can do it a little bit later.
One AVAudioPlayer can only play one audio, and if you want to mix you can create multiple instances of AVAudioPlayer, each equivalent to one track on the mixing board.
1. Create 1 player


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


AVAudioPlayer* player = [[AVAudioPlayer alloc] 
                            initWithData:myData  
                            error:&err ];// use NSData create  

As I said before, AVAudioPlayer can't play network URL, but it can play NSData. We seem to be inspired. We can create NSData through network URL, and then play NSData through AVAudioPlayer. However, this method is not recommended, because AVAudioPlayer can only play one complete file and does not support streaming playback, so it must be buffered before playing. Therefore, if the network file is too large or the network speed is not enough, you will have to wait a long time. So when we play network audio we usually use audio queues.
2. Player attributes
Once you have created an AVAudioPlayer, you can access or set its various properties.
Volume 1.

player.volume=0.8;//0.0~1.0 between  

2. Number of cycles

player.numberOfLoops = 3;// Play only by default 1 time  

3. Playing position

player.currentTime = 15.0;// You can specify where to start playback  

4. Track number

NSUInteger channels = player.numberOfChannels;// Read-only property

5. Duration

NSTimeInterval duration = player.dueration;// Gets the duration of the sampling

6. Meter count

player.meteringEnabled = YES;// Turn on the meter counting function  
[ player updateMeters];// Update meter reading  
// Read the average level and peak level of each channel, representing the decibel level of each channel , In the range -100 ~ 0 In between.  
for(int i = 0; i<player.numberOfChannels;i++){ 
float power = [player averagePowerForChannel:i]; 
float peak = [player peakPowerForChannel:i]; 


3. Play sound
I've been preparing for so long. I'm so excited to finally play it.

[ player prepareToPlay];// Allocate the resources required for playback and add them to the internal playback queue  
[player play];// play  
[player stop];// stop  

Do you feel ready for so long, 1 immediately over, too fast, don't worry, there are a few key.
4. Proxy method
There is an exception to join the play, or the higher level system task interrupted, our program has not finished in time to hang, how to do. There's no hurry, we can handle all of these very nicely with a couple of delegate methods.
First it is necessary to set the delegate to player:

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

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

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

- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{ 
    // Code that handles interrupts  

- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{ 
    // Code that handles the end of the interrupt  


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


Related articles: