Background playback Summary for iOS audio

Source: Internet
Author: User

In the absence of the network, the background of audio playback is relatively simple, Google can search for a lot of information, but if each song request is through the network, it is not, and sometimes can not carry a few, here summarizes the implementation method, you can achieve the same functions as the radio, background play, network request song, Remote control, lock screen has cover, phone and listen to songs interrupt processing.

Initializing Audiosession and basic configuration

The audio player adopts the avplayer, its own function encapsulation, for the time being, when the program starts, it is necessary to configure the audiosession,audiosession is responsible for the application of audio settings, such as support does not support the background, interrupt and so on, this step is very important, For example, after initializing Avplayer in Viewdidload, call the following function:

-(void) setaudiosession{

Audiosessioninitialize used to control interrupts, which will be said later

Audiosessioninitialize (

NULL,//' null ' to use the default (main) run loop

NULL,//' null ' to use the default run loop mode

Asaudiosessioninterruptionlistener,//a reference to your interruption callback

NULL//data to pass to your interruption listener callback

);

This way backstage, can continuously play non-network request song, encounter network request song on the scrap, need background to apply for task

Avaudiosession *session = [Avaudiosession sharedinstance];

Nserror *setcategoryerror = nil;

BOOL success = [Session Setcategory:avaudiosessioncategoryplayback error:&setcategoryerror];

if (!success)

{

/* Handle the error condition */

Return

}

Nserror *activationerror = nil;

Success = [Session Setactive:yes error:&activationerror];

if (!success)

{

/* Handle the error condition */

Return

}

}

Audiosessioninitialize is used to handle interrupt handling, avaudiosession primarily calls Setcategory and SetActive methods to set up, Avaudiosessioncategoryplayback is typically used to support background playback, and other types can be seen in official documents, each for a different occasion:

123456789101112131415161718192021 NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_ref/doc/c_ref/ Avaudiosessioncategoryambient "] [><blockquote]] > Avaudiosessioncategoryambient</blockquote] >< /A]] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_ref/doc/c_ref/ Avaudiosessioncategorysoloambient "] [><blockquote]] > Avaudiosessioncategorysoloambient</blockquote]] &GT;&LT;/A]] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.Ioslibrary.docset/contents/resources/documents/documentation/avfoundation/reference/avaudiosession_ Classreference/reference/reference.html#//apple_ref/doc/c_ref/avaudiosessioncategoryplayback "] >< BLOCKQUOTE] [] > Avaudiosessioncategoryplayback</blockquote]] ></a] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_ref/doc/c_ref/ Avaudiosessioncategoryrecord "] [><blockquote]] > Avaudiosessioncategoryrecord</blockquote]] ></a ]] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ Avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_rEf/doc/c_ref/avaudiosessioncategoryplayandrecord "] [><blockquote]] > Avaudiosessioncategoryplayandrecord </blockquote] [></a]] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_ref/doc/c_ref/ Avaudiosessioncategoryaudioprocessing "] [><blockquote]] > avaudiosessioncategoryaudioprocessing</ BLOCKQUOTE] [></a]] >; NSString *const <a href= "file:///Users/lipengxuan/Library/Developer/Shared/Documentation/DocSets/ com.apple.adc.documentation.appleios6.0.ioslibrary.docset/contents/resources/documents/documentation/ avfoundation/reference/avaudiosession_classreference/reference/reference.html#//apple_ref/doc/c_ref/ Avaudiosessioncategorymultiroute "] [><blockquote]] > Avaudiosessioncategorymultiroute</blockquoTE]] [></a]] >;

1

In addition to the initialization of the code, an important step is to set the info-plist so that the app supports audio background playback

The introduction of libraries includes:

Audiotoolbox.framework

Mediaplayer.framework

Coremedia.framework

Avfoundation.framework

Background playback

Normally, if you configure the Avaudiosessioncategoryplayback method and modify the Info-plist file, the app already supports background audio playback, but if every song doesn't exist locally, it's not in the network. Need to apply for background tasks to process, first modify:

-(void) Applicationdidenterbackground: (uiapplication *) Application {

[Application beginreceivingremotecontrolevents];
}

Then add in the player's play function:

-(void) justplay{

Uibackgroundtaskidentifier bgtask = 0;

if ([uiapplication sharedapplication].applicationstate== uiapplicationstatebackground) {

NSLog (@ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx background play");

[Theplayer play];

Uiapplication*app = [UIApplication sharedapplication];

Uibackgroundtaskidentifier newtask = [app Beginbackgroundtaskwithexpirationhandler:nil];

if (bgtask!= uibackgroundtaskinvalid) {

[App Endbackgroundtask:bgtask];

}

Bgtask = NewTask;

}

else {

NSLog (@ "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx front desk play");

[Theplayer play];

}

}

This can be played in front of the foreground or the background of the judgment, support the network backstage play, a first continuous play.

Remote control

Add these two functions to the viewcontroller of the playback view:

-(void) Viewdidappear: (BOOL) Animated {

NSLog (@ "Viewdidappear!!!");

[Super viewdidappear:animated];

Once The view has loaded then we can register to begin recieving controls and we can become the first responder

[[UIApplication sharedapplication] beginreceivingremotecontrolevents];

[Self becomefirstresponder];

}

-(void) Viewwilldisappear: (BOOL) Animated {

NSLog (@ "Viewwilldisappear!!!");

[Super viewwilldisappear:animated];

End recieving Events

[[UIApplication sharedapplication] endreceivingremotecontrolevents];

[Self resignfirstresponder];

}

Of course, you can also put in the same way into the DELEGATE.M inside the backstage and back to the foreground function, otherwise, the above code only allows the current view of the case into the background can be remote control

Then add the following code:

-(void) Remotecontrolreceivedwithevent: (uievent *) event{

If it is a remote control event handle it correctly

if (Event.type = = Uieventtyperemotecontrol) {

if (Event.subtype = = Uieventsubtyperemotecontroltoggleplaypause) {

[Self playertap];

} else if (Event.subtype = = Uieventsubtyperemotecontrolnexttrack) {

[Self nextsongauto];

[Self confignowplayinginfocenter];

}

}

}

Make sure we can recieve remote control events

-(BOOL) Canbecomefirstresponder {

return YES;

}

Lock screen Cover

This method is usually called every time you switch songs or update information.

-(void) Confignowplayinginfocenter {

Nsdictionary *albumdic=[currentparsersongarray Objectatindex:songindex];

if (nsclassfromstring (@ "Mpnowplayinginfocenter")) {

Nsmutabledictionary * Dict = [[Nsmutabledictionary alloc] init];

[Dict setobject:[albumdic objectforkey:@ "name"] forkey:mpmediaitempropertytitle];

[Dict setobject:[albumdic objectforkey:@ "singer"] forkey:mpmediaitempropertyartist];

[Dict setobject:[albumdic objectforkey:@ "album"] Forkey:mpmediaitempropertyalbumtitle];

Mpmediaitemartwork * MArt = [[Mpmediaitemartwork alloc] initWithImage:cdCoverImgView.image];

[Dict Setobject:mart forkey:mpmediaitempropertyartwork];

[Mpnowplayinginfocenter defaultcenter].nowplayinginfo = nil;

[[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:dict];

}

}

Interrupt processing

Try the official documents on the various proxy methods, interrupt notification, are useless, and then use C function processing can control the interruption, first audiotoolbox.framework is needed to introduce

The Asaudiosessioninterruptionlistener function is called when the session is set, that is, the implementation of the class to which the interrupt is to be added.

Add this static method @implementation front

static void Asaudiosessioninterruptionlistener (void *inclientdata, UInt32 ininterruptionstate)

{

[[Toolmanager Defaultmanager] handleinterruption:ininterruptionstate];

}

Each interrupt end or start will call this method, ininterruptionstate to determine whether it is the beginning or the end, because it is a C function, can not directly call the class [self xxx] method, notification is useless, so write a singleton class, receive this parameter, and then to judge

-(void) Handleinterruptionchangetostate: (nsnotification *) notification

{

Audioqueuepropertyid Ininterruptionstate=[[notification Object] longvalue];

if (ininterruptionstate = = kaudiosessionbegininterruption)

{

NSLog (@ "begin interruption ——->");

}

else if (ininterruptionstate = = kaudiosessionendinterruption)

{

NSLog (@ "End interruption ——->");

}

}

Background playback Summary for iOS audio

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.