Several ways to play audio on IOS

Source: Internet
Author: User
Tags file url

The IPhone OS mainly offers several ways to play audio:

    • System Sound Services
    • Avaudioplayer class
    • Audio Queue Services
    • OpenAL

1. System Sound Services

System Sound Services is the lowest and simplest voice playback service, and calling Audioservicesplaysystemsound This method can play some simple audio files, using this method is only suitable for Play some very small hints or warning tones because it has a lot of limitations:

Sound length less than 30 seconds
In linear PCM or IMA4 (IMA/ADPCM) format
Package as. CAF,. AIF, or. wav files
Cannot control the progress of playback
Play sound immediately after calling method
No loop playback and stereo control

In addition, it can call the system's vibration function, the method is also very simple. The specific code can refer to the official example Syssound
, but the official example only has some simple usage, from the document we find that we can add CallBack function for audio playback through the Audioservicesaddsystemsoundcompletion method, with CallBack function we can solve many problems, For example, you can overcome the problem that System sound Services does not natively support looping playback.

2. Avaudioplayer class

Avaudioplayer is a class defined in Avfoundation.framework, so the use is to first introduce avfoundation.framework in the project. We can think of Avaudioplayer as an advanced player that supports a wide range of audio formats, mainly in the following formats:

AAC
AMR (Adaptivemulti-rate, Aformatforspeech)
ALAC (applelossless)
ILBC (Internetlowbitratecodec, Anotherformatforspeech)
IMA4 (IMA/ADPCM)
LINEARPCM (Uncompressed)
Μ-lawanda-law
MP3 (Mpeg-1audiolayer3

Avaudioplayer can play audio files of any length, support looping, play multiple audio files simultaneously, control playback progress and start playback from any point in the audio file, and more advanced features can refer to Avaudioplayer's documentation. To play a file using Avaudioplayer objects, you only need to specify an audio file for it and set a delegate object that implements the Avaudioplayerdelegate protocol.

As soon as the Numberofloops property of Avaudioplayer is set to a negative number, the audio file will loop until the Stop method is called.

Avaudioplayer also supports Callback, which is an optional delegate method for Avaudioplayerdelegate:

-(void ) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL ) Flag {

if (player = = self. Player && flag = = YES) {

NSLog (@ "Playback finish.");

}

}

In addition, you can control the playback, pause and stop of the Avaudioplayer object at any time, by judging the state of the object, call the play, pause and stop methods respectively:

-(Ibaction) Playorpause: (ID ) Sender {

If playing, pause

if ( self. player.playing) {

[ self. Player pause];

If stopped or paused, start playing

} Else {

[ self. Player play];

}

Although the Avaudioplayer can play a lot of formats, but in the actual development process is still best to use some non-compressed format, such as WAVE files, which can reduce the system processing unit resource consumption, in order to better complete the program's other functions. In addition, when using Avaudioplayer to continuously play MP3 such compressed audio files, there may be a certain interval at the junction.

3. Audio Queue Services

If the two audio playback solutions do not meet your needs, then I think you will definitely need to use audio Queue Services. With audio Queue Services, you can fully control the sound by playing it. For example, you can perform a fast/slow playback of audio when sound data is read from a file to a memory buffer and then played back.

Because audio queue services is a lot more complex, Apple officials have organized it into a book, which can be found in the program examples of audio Queue Services Programming Guide and Speakhere.

4. OpenAL

OpenAL is a cross-platform, open-source audio processing interface, similar to the graphics-processing OpenGL, which provides a more optimized solution for audio playback. It is ideal for developing game sounds and uses the same as other platforms.

This article is mainly about Avaudioplayer,

The Avaudioplayer class encapsulates the ability to play a single sound. Players can be initialized with Nsurl or nsdata, note that Nsurl can not be a network URL and must be a local file URL, because Avaudioplayer does not have the ability to play network audio.

A avaudioplayer can only play one audio, and if you want to mix you can create multiple Avaudioplayer instances, each equivalent to a track on the mixer board.

One, create a player

Avaudioplayer *player = [[Avaudioplayeralloc] initwithcontentsofurl:[nsurlfileurlwithpath:[[nsbundlemainbundle] Pathforresource:@ "star Moon Myth" oftype:@ "MP3"] error:nil]; //Create with local URL

Avaudioplayer *player = [[Avaudioplayer alloc] Initwithdata:data error:nil];//created with NSData

I've said before that Avaudio can not play the network URL, but can play nsdata, we seem to be inspired, we can go through the network URL to create NSData, and then through the Avaudioplayer to play nsdata, so that can play the network 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 is not enough speed is not to wait a long time? So play the network audio we generally use the audio queue.

Second, player properties

After you create a avaudioplayer, you can access or set up its various properties.

1. Volume

Between Player.volume =0.8;//0.0-1.0

2. Number of Cycles

Player.numberofloops =3;//play only once by default

3. Playback position

Player.currenttime =15.0;//can specify to start playback from any position

4. Number of channels

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

5. Duration

Nstimeinterval Duration = player.duration;//Get duration

6. Meter Counting

player.meteringenabled =yes;//turn on meter count function

[playerupdatemeters];//Update Gauge count


Third, play the sound

[Player preparetoplay];//allocates the required resources for playback and joins them to the internal play queue

[playerplay];//Playback

[playerstop];//Stop

Iv. Agent Methods

This class corresponds to the avaudioplayerdelegater of the delegate method. Audioplayerdidfinishplaying:successfully: Triggered when audio playback is complete. When playback is complete, you can reset the playback button's text back to: Play Audio File

-(void) audioplayerdidfinishplaying: (Avaudioplayer *) player successfully: (BOOL) flag

{

Actions performed at end of playback

[Audiobutton settitle:@ "Play Audio File" forstate:uicontrolstatenormal];

}

-(void) Audioplayerdecodeerrordidoccur: (Avaudioplayer *) Player ERROR: (NSERROR *) error;

{

Decoding the actions performed by the error

}

When a call comes in while it's playing, the call can be used to save the playback information.

-(void) Audioplayerbegininterruption: (Avaudioplayer *) player;

{

Code to handle interrupts

}

Audioplayerendinterruption: When the program is interrupted by an external application, it is triggered back to the application. When you return to this application here, continue playing the music.

-(void) Audioplayerendinterruption: (Avaudioplayer *) player

{

[Audioplayer play];

}

Avaudioplayer introduced to this.

Several ways to play audio on IOS

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.