Music player based on Avplayer

Source: Internet
Author: User

1, recently wrote a music player on the demo, access to the information process, learned a lot of new things. A simple record of the process of writing encountered problems, Memo.

2, for ease of use, the player is written as a single case. h

Import the required libraries first

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

#import <objc/runtime.h>

Generate an instance of a player

@property (Nonatomic,strong) Avplayer *avplay;

@property (Nonatomic,strong) Avplayeritem *avitem;

3, implementing methods in. m files

Avplay = [[Avplayer alloc] init];

Add a notification to play complete

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (playbackfinished:) Name: Avplayeritemdidplaytoendtimenotification Object:AVplay.currentItem];

-(void) playbackfinished: (nsnotification *) notification{

/*

The play is done here, such as playing the next song

*/

}

4, initialize the link to play

Avitem = [[Avplayeritem alloc] Initwithurl:[nsurl Urlwithstring:url]];

[Avplay Replacecurrentitemwithplayeritem:avitem];

5. Click the Play button to control playback and pause

_isplaying =!_isplaying;

if (_isplaying) {

[Self resume]; Start/Resume Playback

}else{

[Self pause]; Time out

}

-(void) resume{

[Avplay play];

}

-(void) pause{

[Avplay pause];

}

6, the previous song, the next song call 4 method, Avitem re-assign the value

7, get the current playback progress, assign a value to the progress bar

-(float) progress{

float percentage = (cmtimegetseconds (AVplay.currentItem.currentTime)/cmtimegetseconds (AVplay.currentItem.duration ));

return percentage;

}

8, get the value after the progress bar moved, adjust the playback progress

-(void) Movetosection: (cgfloat) section{

int32_t timescale = AVplay.currentItem.asset.duration.timescale;

Float64 playersection = cmtimegetseconds (AVplay.currentItem.duration) * section;

[Avplay seektotime:cmtimemakewithseconds (playersection, timescale) Tolerancebefore:kcmtimezero ToleranceAfter: Kcmtimezero];

}

9, in order to achieve background playback

Background Playback set Audio session type

Need to import header file #import <AVFoundation/AVFoundation.h>

Avaudiosession *session = [Avaudiosession sharedinstance];

Nserror *setcategoryerror = nil;

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

if (!success)

{

Return

}

Nserror *activationerror = nil;

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

if (!success)

{

Return

}

Also find Required background modes in Info.plist file, add key value Select App plays audio or streams audio/video using AirPlay

10, to display the playback information when the lock screen is implemented

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

Let apps run in the background

[Application Beginbackgroundtaskwithexpirationhandler:nil];

In order to display the contents of the lock screen state

[[UIApplication sharedapplication] beginreceivingremotecontrolevents];

[Self becomefirstresponder]; Corresponding event

Refresh the lock screen when you first enter the background

[[Playmanager sharedinstance] configplayinginfo];

}

Determine the time type

-(void) Remotecontrolreceivedwithevent: (Uievent *) event

{

if (Event.type = = Uieventtyperemotecontrol) {

Switch (event.subtype) {

Case Uieventsubtyperemotecontrolplay:

[[Playmanager sharedinstance] resume]; Play

Break

Case Uieventsubtyperemotecontrolpause:

[[Playmanager sharedinstance] pause];//Pause

Break

Case Uieventsubtyperemotecontrolprevioustrack:

[[Playmanager sharedinstance] last]; Play the previous Song button

Break

Case Uieventsubtyperemotecontrolnexttrack:

[[Playmanager Sharedinstance] next]; Play next Song button

Break

Default

Break

}

}

}

After entering the front desk, cancel the corresponding

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

[[UIApplication sharedapplication] endreceivingremotecontrolevents];

[Self resignfirstresponder];

}

11. How the lock screen displays content

-(void) configplayinginfo{

if (_currentmodel!=nil) {

if (nsclassfromstring (@ "Mpnowplayinginfocenter")) {

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

[Dict setobject:_currentmodel.title forkey:mpmediaitempropertytitle];//song name settings

[Dict setobject:_currentmodel.source_name forkey:mpmediaitempropertyartist];//singer name settings

[Dict setobject:[[mpmediaitemartwork alloc] initwithimage:[uiimage imagenamed:@ "Car"] Forkey: mpmediaitempropertyartwork];//album picture settings

[Dict setobject:[nsnumber Numberwithdouble:cmtimegetseconds (AVplay.currentItem.currentTime)] Forkey: Mpnowplayinginfopropertyelapsedplaybacktime]; Music is currently playing time

[Dict Setobject:[nsnumber numberwithfloat:1.0] The speed of the forkey:mpnowplayinginfopropertyplaybackrate];//progress cursor (this with Own playback rate adjustment, I default is the original speed play)

[Dict setobject:[nsnumber Numberwithdouble:cmtimegetseconds (AVplay.currentItem.duration)] Forkey: mpmediaitempropertyplaybackduration];//Song Total time setting

[[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:dict];

}

[Atworkimg Sd_setimagewithurl:[nsurl Urlwithstring:_currentmodel.cover_url] completed:^ (UIImage *image, NSError * Error, Sdimagecachetype CacheType, Nsurl *imageurl) {

Lock screen display of the picture is the network, download and then switch, or there will be problems

Nsdictionary *dic = [[Mpnowplayinginfocenter defaultcenter] nowplayinginfo];

Nsmutabledictionary *mudic = [[Nsmutabledictionary alloc] initwithdictionary:dic];

[Mudic Setobject:[[mpmediaitemartwork alloc] initWithImage:atWorkImg.image] forkey:mpmediaitempropertyartwork];

[[Mpnowplayinginfocenter Defaultcenter] setnowplayinginfo:mudic];

}];

}

}

No handling of interruptions for the time being

Music player based on Avplayer

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.