Play Music in IOS background

Source: Internet
Author: User

IOS 4 started with the introduction of the multitask, we can achieve the same as the ipod program in the background to play audio. If the audio operation is implemented with the official Apple Avfoundation.framework, like playing with Avaudioplayer,avplayer, to achieve the perfect background audio playback, depending on the function of the app, you may need to implement several key functions.

First of all, to set the Avaudiosession mode before playing the audio, usually only for playing the app can be set to Avaudiosessioncategoryplayback. Please refer to the documentation for the mode meaning and other modes.

1//Background playback audio Settings 2 avaudiosession *session = [Avaudiosession sharedinstance];3 [Session setactive:yes error:nil];4 [session SE Tcategory:avaudiosessioncategoryplayback Error:nil];

1. Notify iOS that the app supports background audio. By default, when the home key is pressed, the currently running program is suspend and the state changes from active to in-active, that is, if the audio is playing, it will stop when you press home. Here you need to let the app at home, go to the background to run instead of being suspend, the solution is to add required background modes This key item in the program's-info.plist, and select the app plays audio or Streams Audio/video using Airplay this value entry (if used Xcode5.0, on Targets-capabilities-background modes set to ON, select audio and Airplay option).

2. If you are playing in the background to load the network audio, it happens that the speed is slow, the audio is stopped at this time the program also suspend, there has been a cottage solution is dedicated to a player instance continuously put the same no sound fragment, block program was suspend. The method provided here is to use the background taskid to achieve the background switch to play the file function.
Even if you declare TaskID, you can run up to 600 seconds in the background. (Nsurlsession can be used in IOS7SDK to enable background buffering)
(in general, press home to send the program to the background, you can have 5 or 10 seconds to do some finishing work, specific time [[UIApplication sharedapplication] backgroundtimeremaining] return value, The app will be suspend after timeout. )

3.ipod player in the background, double-click the Home button, there will be a control interface, you can play control of it (pause, Previous, next song). If you want your app to be in the background like an ipod, you can easily control it by double-clicking the Home button (using the Pull-up menu control in iOS7), you need to use the remote control event.
First, declare the app to receive remote control events and end the declaration at the place where the viewdidload is initialized.

-(void) Viewwillappear: (BOOL) Animated{[super viewwillappear:animated];[ UIApplication sharedapplication] beginreceivingremotecontrolevents]; [Self becomefirstresponder];} -(void) Viewwilldisappear: (BOOL) Animated{[super viewwilldisappear:animated];[ UIApplication sharedapplication] endreceivingremotecontrolevents]; [Self resignfirstresponder];} -(BOOL) canbecomefirstresponder{       return YES;

Of course, it is not necessarily in the viewcontroller, it can also be in the Applicationdidenterbackground: Method begins to accept remote control, applicationdidbecomeactive: In the end to accept remote control, However, the current appdelegate is inherited from Uiresponder because the current class becomes the first response after activating the remote control, overriding the Canbecomefirstresponder method.

Finally define the remotecontrolreceivedwithevent to deal with specific events such as play, pause, forward, rewind, etc.

//overrides the parent class method, accepting processing of external events-(void)        Remotecontrolreceivedwithevent: (uievent *) receivedevent {if (Receivedevent.type = = Uieventtyperemotecontrol) { Switch (receivedevent.subtype) {case uieventsubtyperemotecontroltoggleplaypause: [Self Playan                DStopSong:self.playButton];            Break                Case Uieventsubtyperemotecontrolprevioustrack: [Self PlayLastButton:self.lastButton];            Break                Case Uieventsubtyperemotecontrolnexttrack: [Self PlayNextSong:self.nextButton];            Break                Case Uieventsubtyperemotecontrolplay: [Self PlayAndStopSong:self.playButton];            Break                Case Uieventsubtyperemotecontrolpause: [Self PlayAndStopSong:self.playButton];            Break        Default:break; }    }}

Other external events can also be implemented in this way, such as "shake-and-shake" responses.

4. At this point, you have the play app has been basically completed, and then Plug and unplug the headset to respond to stop playing time need to further study the headset detection and voice routing issues, again not detailed.

5. Some developers may find that some audio and video apps customize some controls to adjust the volume of the system, without requiring the user to adjust the volume buttons. There are two ways to summarize the relevant data:
One is to call the control Mpvolumeview create a volume bar on the screen, and drag to change the volume of the system.
Another is to use the Mpmusicplayercontroller class, you can customize the control to adjust the size of the system volume (but has been deprecated in ios7sdk, it is estimated that this method may not be found in the next few versions).

Mpmusicplayercontroller *MPC = [Mpmusicplayercontroller applicationmusicplayer];mpc.volume = 0;  0.0~1.0

6. In some other music playing software such as: Cool, QQ music, etc., you will be sent in the play, when the device lock screen will still be able to see the user playing music name, singer, album name, Music time, album pictures and other information. This will require the user to set up the information in the program when they have finished switching songs.

Set the lock screen status, display the song Information-(void) confignowplayinginfocenter{if (nsclassfromstring (@ "Mpnowplayinginfocenter")) {Nsdiction        ary *info = [Self.musiclist objectatindex:_playindex];        Nsmutabledictionary *dict = [[Nsmutabledictionary alloc] init];        Song name [dict setobject:[info objectforkey:@ "name"] forkey:mpmediaitempropertytitle];        Singers [Dict setobject:[info objectforkey:@ "singer"] forkey:mpmediaitempropertyartist];        Album name [Dict setobject:[info objectforkey:@ "album"] Forkey:mpmediaitempropertyalbumtitle];        Album thumbnails UIImage *image = [UIImage imagenamed:[info objectforkey:@ "image"];        Mpmediaitemartwork *artwork = [[Mpmediaitemartwork alloc] initwithimage:image];        [Dict setobject:artwork forkey:mpmediaitempropertyartwork]; Length of music remaining [Dict Setobject:[nsnumber NumberWithDouble:self.player.duration] Forkey:mpmediaitempropertyplaybackdurati        On]; Music current playback time in timer modify//[dict setobject:[nsnumber Numberwithdouble:0.0] Forkey:mpnowplayinginfopropertyelapsedplaybacktime];    Set the screen display to play music information [[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:dict]; }}

The above if (Nsclassfromstring (@ "Mpnowplayinginfocenter")) statement, said to avoid version compatibility issues, this API appears to appear only in 5.

7. The playback progress bar in the lock screen state is constantly refreshed in the timer.

Timer modification Progress-(void) Changeprogress: (Nstimer *) sender{    if (self.player) {        //Current playback time        Nsmutabledictionary * Dict = [nsmutabledictionary dictionarywithdictionary:[[mpnowplayinginfocenter defaultcenter] nowPlayingInfo]];        [Dict setobject:[nsnumber NumberWithDouble:self.player.currentTime] Forkey: Mpnowplayinginfopropertyelapsedplaybacktime]; The music is currently out of date        [[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:dict];}    

8. The current many common players can display the lyrics in the lock screen state, after a search, finally found the method (details: Click to view), roughly based on the time and lyrics display time, using the timer constantly using lyrics and album cover to synthesize pictures, to show the effect of lyrics. There are two ways to monitor the phenomenon when the screen dims to stop this operation and the screen is lit to start the timer to conserve power and CPU.
One is listening to the kernel layer darwinnotification, there are a lot of system events in Darwin, but Apple's API documentation describes these APIs using a limited, gray-area API, so you don't have to.
Another method can get the status value of Com.apple.springboard.hasBlankedScreen through notify_get_state, we can judge the screen state by the state value, the screen light or dark system will give different status values, Then, according to the status value, send a message notification via notificationcenter to the corresponding function processing.

From:http://www.cnblogs.com/easy-coding/p/3569227.html


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Play Music in IOS background

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.