Play Music on iOS

Source: Internet
Author: User

HTTP://WWW.JIANSHU.COM/P/CE279BC773DD first of all to put a StreamingkitThe link

Simple playback using examples, you can see the open source author's demo demo.

Because the whole player involves the UI AH data ah more, so it is not all cut down when the demo, it is here to list a little tips, hope to help everyone.

Song playback Form I wrote this:
. h:/** song playback form */typedef Enum:nsuinteger {mbaudioplaytypecircle,//looping mbaudioplaytyperandom,//Random play Mbaudi oplaytypeonemusic,//single cycle Mbaudioplaytypenonext,//broadcast end will not broadcast} Mbaudioplaytype;. M-li:/** * next */-(void) playnextmusic{switch (self.playtype) {case mbaudioplaytypecircle: {//follow            Ring Play _nowmusiclocal++;            if (_nowmusiclocal >= [self alllocal]) {_nowmusiclocal = 0;        } [self playmusic];        } break;            Case Mbaudioplaytyperandom: {//Shuffle [self randomwithtimes:5];            if (_nowmusiclocal >= [self alllocal]) {_nowmusiclocal = 0;        } [self playmusic];        } break;        Case Mbaudioplaytypeonemusic: {//single loop [self playmusicwithinfo];        } break;        Case Mbaudioplaytypenonext: {//Will not be broadcast after play} break; DEfault:break;  }} #pragma mark-random random number/** * Random recursion * * @param num recursion count */-(void) Randomwithtimes: (nsinteger) num{Nsinteger randommusic    = Arc4random ()% [self alllocal];    DLog (@ "Random value:%ld", (long) randommusic); if (_nowmusiclocal = = Randommusic && [self alllocal]! = 1) {//Prevent recursive dead loop if (num! = 0) {nu            m--;            [Self randomwithtimes:num];        Return            }else {randommusic++;        Recursive multiple times also, it is forced to set a (low probability event) _nowmusiclocal = Randommusic;    }} else {//normal case _nowmusiclocal = Randommusic; }}

This random algorithm writes actually quite rubs, but can barely use it ...

Get Background Play permissions

Open audio and airplay in Target-capabilities-background modes

In the Appdelegate

#import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    xxxxx;NSError* error;    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];}

# # #漏掉最重要的了, when the program hangs, to manually add permissions,

-(void) Applicationwillresignactive: (uiapplication *) application{DLog (@ "\ n \ nthe stubborn line of words tell you I want to hang up. \ n ");//mbaudioplayer is a single case I wrote for the player, this is when the music is still playing state, to the background permission, not playing the state of the time, back to the background permission if ([Mbaudioplayer shareinstance]. Audioplayer.state = = Stkaudioplayerstateplaying| | [Mbaudioplayer shareinstance].audioplayer.state = = Stkaudioplayerstatebuffering| | [Mbaudioplayer shareinstance].audioplayer.state = = Stkaudioplayerstatepaused | |        [Mbaudioplayer shareinstance].audioplayer.state = = stkaudioplayerstatestopped) {//have music playback, only give background permission, do not do rogue application.        [[UIApplication sharedapplication] beginreceivingremotecontrolevents];        [Self becomefirstresponder];        Open Timer [[Mbaudioplayer shareinstance] Decidetimerwithtype:mbaudiotimerstartbackground Andbeginstate:yes];    [[Mbaudioplayer shareinstance] confignowplayinginfocenter];        } else {[[uiapplication sharedapplication] endreceivingremotecontrolevents];        [Self resignfirstresponder]; Detect is both off timer [[MbaudioplayER shareinstance] decidetimerwithtype:mbaudiotimerstartbackground andbeginstate:no]; }}
When the screen is locked, update the console, lock screen information (timer call)
#pragma mark-Lock screen control/** * Set lock screen information */-(void) confignowplayinginfocenter{if (self.nowplayingmusicinfo = = nil) {RET    Urn        } @autoreleasepool {Nsdictionary *info = Self.nowplayingmusicinfo;        Nsmutabledictionary *dict = [[Nsmutabledictionary alloc] init];        Song name [dict setobject:[info objectnullforkey:@ "title"] Forkey:mpmediaitempropertytitle];        Singers [Dict setobject:[info objectnullforkey:@ "author"] forkey:mpmediaitempropertyartist];        Album name//[dict setobject:[info objectnullforkey:@ "album"] Forkey:mpmediaitempropertyalbumtitle];        Album thumbnails nsstring *imagepath = [info objectnullforkey:@ "thumb"];        ImagePath = [NSString stringwithformat:@ "Egoimageloader-%lu", (unsigned long) [[ImagePath description] hash]];        NSString *imagelocalpath = [NSString stringwithformat:@ "%@/%@", Egocachedirectory (), ImagePath];        NSData * Thumbdata = [NSData Datawithcontentsoffile:imagelocalpath]; if (thumbdata! = nil) {UIImage *image = [UIImage imagewithdata:thumbdata];            Mpmediaitemartwork *artwork = [[Mpmediaitemartwork alloc] initwithimage:image];        [Dict setobject:artwork forkey:mpmediaitempropertyartwork]; }else {//fixme: No graph, read graph}//music remaining length [dict setobject:[nsnumber numberwithdouble:s        Elf.audioPlayer.duration] forkey:mpmediaitempropertyplaybackduration]; The current playback time of the music is modified in the timer [dict setobject:[nsnumber numberWithDouble:self.audioPlayer.progress] Forkey:mpnowplayinginfopro        Pertyelapsedplaybacktime];        Set the screen display to play Music information//dlog (@ "Show music information:%@\n%@", Dict,[info objectnullforkey:@ "title"]);    [[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:dict]; }}/** * response to remote music playback Control Message * * @param receivedevent */-(void) Remotecontrolreceivedwithevent: (uievent *) receivedevent {if (Receivedevent.type = = Uieventtyperemotecontrol) {switch (receivedevent.subtype) {case UieventsubtyPeremotecontrolpause://clicked Pause [self pausestreamer];            Break                Case Uieventsubtyperemotecontrolnexttrack://Click Next [Self playnextmusic];            Break                Case Uieventsubtyperemotecontrolprevioustrack://Click on previous [self playpremusic];            You need to change the song information at this time.                Case Uieventsubtyperemotecontrolplay://clicked play [Self pausestreamer];            Break        Default:break; }    }}
Finally, those with lyrics in the lock screen products, it is said that the lyrics and album Pictures together, and then according to the lyrics time to refresh the picture ... If there is a demand for this product, you can do it according to this idea.

Play Music on iOS

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.