Audio service and audio Avaudioplayer Audio player usage guide in IOS _ios

Source: Internet
Author: User
Tags file url

Audioservicesplaysystemsound Audio Service
for simple, no-mix audio, the Avaudio Toolbox Framework provides a simple C-language-style audio service. You can use the Audioservicesplaysystemsound function to play simple sounds. Follow these rules:
1. Audio length less than 30 seconds
2. The format can only be PCM or IMA4
3. Files must be stored as. CAF,. AIF, or. wav format
4. Simple audio can not play from memory, but only disk files
In addition to the restrictions on simple audio, your way of audio playback is basically out of control. Once the audio playback starts immediately, it is the volume playback that is set by the current phone consumer. You will not be able to loop the sound or control the stereo effect. But you can still set a callback function to be called at the end of the audio playback, so you can clean up the audio object and notify your program to play it over.
Directly on the code:

Copy Code code as follows:

#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) {
/* Playback is complete, so release all resources/
Audioservicesdisposesystemsoundid (sample);
Cfrelease (sample);
Cfrunloopstop (Cfrunloopgetcurrent ());
}
Main loop
int main () {
/* System audio ID, used to register the sound we will be playing * *
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 audio at the end of the callback * *
Audioservicesaddsystemsoundcompletion (soundid, NULL, NULL, soundfinished,sample);
/* Start playing * *
Audioservicesplaysystemsound (Soundid);
Cfrunlooprun ();
return 0;
}

Personally feel that this audio service is a bit chicken, but it certainly has its use, such as we want to play a custom warning tone or message prompts, the use of audio services will certainly save resources than other methods.

Avaudioplayer Audio Player
There are three ways to play audio in iOS: Avaudioplayer, audio services, audio queues.
Avaudioplayer in the avfoundation frame, so we're going to import avfoundation.framework.
The Avaudioplayer class encapsulates the ability to play a single sound. The player can initialize with Nsurl or nsdata, note that Nsurl can not be a network URL and must be a local file URL, because the Avaudioplayer does not have the ability to play network audio, but we can use a little way to enable it to have this ability, To be explained later.
A avaudioplayer can play only one audio, and if you want to mix you can create multiple Avaudioplayer instances, each equivalent to one track on the mixer board.
First, create a player

Copy Code code as follows:

#import <AVFoundation/AVFoundation.h>
nserror* err;
avaudioplayer* player = [[Avaudioplayer alloc]
Initwithcontentsofurl:[nsurl Fileurlwithpath:
[[NSBundle Mainbundle]pathforresource:
@ "Music" oftype:@ "M4A"
indirectory:@ "/"]]
Error:&err];//use local URL to create

Copy Code code as follows:

avaudioplayer* player = [[Avaudioplayer alloc]
Initwithdata:mydata
Error:&err];//use NSData to create

I told you before, Avaudioplayer can't play the Web URL, but it can play nsdata, we seem to be inspired, we can create the NSData through the Web URL, and then play NSData through the Avaudioplayer, So is it possible to play online music? But this method is not advisable, because Avaudioplayer can only play a complete file, does not support streaming playback, so must be buffered to play, so if the network file is too large or not enough speed is not to wait a long time? So play network audio we generally use audio queues.
Second, player properties
After you create a avaudioplayer, you can access or set up a variety of its properties.
1. Volume
Copy Code code as follows:

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

2. Cycle times
Copy Code code as follows:

Player.numberofloops = 3;//is played only once by default

3. Play position
Copy Code code as follows:

Player.currenttime = 15.0;//can specify to start playing from anywhere

4. Number of channels
Copy Code code as follows:

Nsuinteger channels = player.numberofchannels;//Read-only property

5. Duration
Copy Code code as follows:

Nstimeinterval Duration = player.dueration;//Gets the duration of the sample

6. Meter Count
Copy Code code as follows:

player.meteringenabled = yes;//turn on meter counting function
[Player updatemeters];//Update meter readings
The average electrical and peak level of each channel is read, representing the decibel number of each channel, ranging between -100~0.
for (int i = 0; i<player.numberofchannels;i++) {
float power = [player averagepowerforchannel:i];
float peak = [player peakpowerforchannel:i];
}

Third, play sound
Prepare for so long, finally can play, mood excited ah.
Copy Code code as follows:

[Player preparetoplay];//assigns the required resources to play and joins it to the internal playback queue
[Player play];//Playback
[Player stop];//stop

Whether feel prepared for so long, suddenly end off, too fast, not urgent, there are a few points.
Iv. Proxy methods
Add to play an exception, or be interrupted by a higher level of system tasks, our program has not yet finished and hung up, how to do? We can handle all situations well through a few delegation methods.
It is necessary to set the delegate first for the player:
Copy Code code as follows:

Player.delegate = self;

Copy Code code as follows:

-(void) audioplayerdidfinishplaying: (avaudioplayer*) player successfully: (BOOL) flag{
Actions performed at end of playback
}
-(void) Audioplayerdecodeerrordidoccur: (avaudioplayer*) Player error: (Nserror *) error{
Decoding the action performed by the error
}
-(void) Audioplayerbegininteruption: (avaudioplayer*) player{
Code to handle interrupts
}
-(void) Audioplayerendinteruption: (avaudioplayer*) player{
Code that handles interrupt completion
}

Knowing this, you can try to make a local player.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.