iOS Development Outreach-Audio processing (music player 4)

Source: Internet
Author: User

iOS Development Outreach-Audio processing (music player 4)

Description: This article mainly introduces some detail control in the process of music player implementation.

The effect of the implementation:

  

One, the complete code

YYPLAYINGVIEWCONTROLLER.M file

  1//2//YYPLAYINGVIEWCONTROLLER.M 3//20-Audio processing (music Player 1) 4//5//Created by Apple on 14-8-13. 6//Copyright (c) 2014 Yangyong.  All rights reserved. 7//8 9 #import "YYPlayingViewController.h" #import "YYMusicTool.h" #import "YYMusicModel.h" #import "Yyaudio Tool.h "@interface Yyplayingviewcontroller () 15//progress bar @property (weak, nonatomic) Iboutlet UIView *progressview ; 17//Slide block @property (weak, nonatomic) Iboutlet UIButton *slider; @property (Weak, nonatomic) Iboutlet Uiimageview *iconview; @property (Weak, nonatomic) Iboutlet UILabel *songlabel; @property (Weak, nonatomic) Iboutlet UILabel *singerlabel; 22//The time of the music currently playing @property (weak, nonatomic) Iboutlet UILabel *durationlabel; 24//Playing music on the @property (Nonatomic,strong) Yymusicmodel *playingmusic; 26//Music Player Object @property (Nonatomic,strong) Avaudioplayer *player; 28//Timer @property (nonatomic,strong) Nstimer *currenttimetimer; -(ibaction) exit; -(Ibaction) TAPPROGRESSBG: (UitapGesturerecognizer *) sender; -(Ibaction) Panslider: (Uipangesturerecognizer *) sender; @end @implementation yyplayingviewcontroller Notoginseng #pragma mark-public Method-(void) Show 39 {40//1. Disable the entire app click Pieces of UIWindow *window=[uiapplication Sharedapplication].keywindow; Window.userinteractionenabled=no; 43 44//2. Add Playback interface 45//Set the view size to cover the entire window self.view.frame=window.bounds; 47//Set view display self.view.hidden=no; 49//Add view to Windows [window AddSubview:self.view]; 51 52//3. Detect if the song is changed if (Self.playingmusic!=[yymusictool Playingmusic]) {[Self Rresetplayingmusi c]; 55} 56 57//4. Use animations to show the view self.view.y=self.view.height;          [UIView animatewithduration:0.25 animations:^{self.view.y=0;] completion:^ (BOOL finished) {62 63//Set music data to [self starplayingmusic]; Window.userinteractionenabled=yes; 66}]; #pragma mark-Private Method 71Reset the music being played Rresetplayingmusic 73 {74//1. Reset interface Data self.iconview.image=[uiimage imagenamed:@ "Play_cove R_PIC_BG "]; Self.songlabel.text=nil; Self.singerlabel.text=nil; 78 79//2. Stop playing [Yyaudiotool StopMusic:self.playingMusic.filename]; 81//The player is emptied by Self.player=nil; 83 84//3. Stop timer [self removecurrenttime]; 86} 87//Start Music data Play-(void) Starplayingmusic 89 {90//1. Set interface Data 91 92//If the music currently playing is the incoming music, then go directly to the         Self.playingmusic==[yymusictool Playingmusic]) 94 {95//Add timer to [self Addcurrenttimetimer]; 97 Return 98} 99//Access Music Self.playingmusic=[yymusictool playingmusic];101 self.iconview.image=[uiimage imageNamed : self.playingmusic.icon];102 self.songlabel.text=self.playingmusic.name;103 self.singerlabel.text= SELF.PLAYINGMUSIC.SINGER;104 105//2. Start playing 106 Self.player = [Yyaudiotool playMusic:self.playingMusic.filename]; 107 108//3. Set length 109//self.player.duration;     The length of time that the player is playing the music file self.durationlabel.text=[self strwithtime:self.player.duration];111 112//4. Adding timers 113 [Self addcurrenttimetimer];114 115}116 117/**118 * Take the length of time--time string 119 */120-(NSString *) Strwithtime: (Nstimeinterv AL) time121 {122 int minute=time/60;123 int second= (int) time% 60;124 return [NSString stringwithformat:@ "%d:     %d ", minute,second];125}126 127 #pragma mark-Timer Control 128/**129 * Add a timer, */131-(void) addCurrentTimeTimer132 {133 First call a progress update in advance to ensure that the timer works in a timely manner 134 [self updatecurrenttime];135 136//Create a timer that is called once per second 137 self. Currenttimetimer=[nstimer scheduledtimerwithtimeinterval:1.0 target:self selector: @selector (updatecurrenttime) Userinfo:nil repeats:yes];138//Add the timer to the runtime 139 [[Nsrunloop mainrunloop]addtimer:self. Currenttimetimer formode:nsrunloopcommonmodes];140}141/**142 * Remove a Timer 143 */144-(void) removeCurrentTime145 {146 [s Elf. Currenttimetimer Invalidate]; 147 148//Empty the timer 149 self.  currenttimetimer=nil;150}151 152/**153 * Update playback Progress 154 */155-(void) updateCurrentTime156 {157//1. Calculate Progress Value 158 double progress=self.player.currenttime/self.player.duration;159 160//2. Calculate the x value of the slider 161//The maximum x value of the slider 162 cgfloat Slide rmaxx=self.view.width-self.slider.width;163 self.slider.x=slidermaxx*progress;164//Set the current playback time on the slider 165 [self.slid     Er settitle:[self strWithTime:self.player.currentTime] forstate:uicontrolstatenormal];166 167//3. Set the width of the progress bar 168 self.progressview.width=self.slider.center.x;169}171 172 #pragma mark-The internal button monitoring method 173//Return button 174-(ibaction) Exit {17 5 176//0. Remove Timer 177 [self removecurrenttime];178//1. Disable click events for entire app 179 UIWindow *window=[uiapplication s haredapplication].keywindow;180 window.userinteractionenabled=no;181 182//2. Animation hidden View183 [UIView Animatewi thduration:0.25 animations:^{184 self.view.y=window.height;185} completion:^ (BOOL finished) {186 window.userinteractionenabled=yes;187//Set view hide to save some performance 188 self.view.hidden=yes;189}];190 }191 192/**193 * Click on the progress bar 194 */195-(ibaction) TAPPROGRESSBG: (UITapGestureRecognizer *) Sender {196//Get the point of the current click 197 C Gpoint point=[sender locationinview:sender.view];198//Toggle song's current playback time 199 self.player.currenttime= (Point.x/sender.view . width) *self.player.duration;200//Update playback Progress 201 [Self updatecurrenttime];202}203 204-(Ibaction) Panslider: (uipanges Turerecognizer *) Sender {205 206//1. Get moved distance 207 cgpoint t=[sender translationinview:sender.view];208//Nudge Clear 209 [Sender Settranslation:cgpointzero inview:sender.view];210 211//2. Control slider and progress bar frame212 self.slider.x+= t.x;213//Set the width of the progress bar 214 self.progressview.width=self.slider.center.x;215 216//3. Set time value 217 cgfloat slider     maxx=self.view.width-self.slider.width;218 double progress=self.slider.x/slidermaxx;219//Current time value = Duration of the music * Current progress Value 220 Nstimeinterval Time=self.player.duration*progress;221 [self. Slider settitle:[self Strwithtime:time] forstate:uicontrolstatenormal];222  223//4. If you start dragging, then stop the timer 224 if (Sender.state==uigesturerecognizerstatebegan) {225//stop timer 226 [self         removecurrenttime];227}else if (sender.state==uigesturerecognizerstateended) 228 {229//Set player playback time 230 self.player.currenttime=time;231//Turn on timer 232 [self addcurrenttimetimer];233}234}235 @end

Ii. Code Description (i)

Adjust to start playing the music button so that it returns a music player, not bool type.

1/** 2  * Play Music 3 */  4 + (Avaudioplayer *) Playmusic: (NSString *) filename 5 {6     if (!filename) return nil;//if not passed in File name, then directly return 7     //1. Remove the corresponding player 8     avaudioplayer *player=[self Musicplayers][filename]; 9     //2. If the player is not created , then initialize one-by-one     if (!player) {         //2.1 audio file URL13         nsurl *url=[[nsbundle mainbundle]urlforresource:filename Withextension:nil];14         if (!url) return nil;//if the URL is empty, then return directly to the         //2.2 create player         player=[[ Avaudioplayer alloc]initwithcontentsofurl:url error:nil];18         //2.3 buffer         if (![ Player Preparetoplay]) return nil;//If the buffer fails, then return it directly to the         //2.4 dictionary         [self musicplayers][filename]= player;24     }25     //3. Play the     if (![ Player IsPlaying]) {         //If it is not currently playing, then play          [player play];30     }31     return player;//is playing, Then return to YES33}

Third, code description (ii)

To convert the time to a time string:

1/**2  * Put the time length--time string 3  */4-(NSString *) Strwithtime: (Nstimeinterval) time5 {6     int minute=time/60;7     int second= (int) Time% 60;8     return [nsstring stringwithformat:@ "%d:%d", minute,second];9}

Iv. Code Description (iii)

Description: Progress Control

Listen to the current playback, using a timer, constant monitoring is currently the first few seconds.

About timer handling: Here are three ways to add timers, remove timers, and update playback progress.

Attention to detail:

(1) After removing the timer, the timer is emptied.

1/** 2  * Remove a Timer 3  */4-(void) Removecurrenttime 5 {6     [self. Currenttimetimer invalidate]; 7      8     //Empty the timer 9 self     . CURRENTTIMETIMER=NIL;10}

(2) When the interface is not visible, stop the timer.

(3) In the beginning of the method of playing music to judge, if the current playing music and incoming music consistent, then add the timer and return directly.

(4) To reset the playback of the music method, stop the timer.

Five, Code description (iv)

Description: Click and drag the Progress bar processing

1. Click on the progress bar

First, add the gesture recognizer that you clicked.

    

To drag the line to the controller:

    

The code involved:

1/** 2  * Click on the progress bar 3 *  /4-(Ibaction) TAPPROGRESSBG: (UITapGestureRecognizer *) Sender {5     //Get the currently clicked Point 6     Cgpoint Point=[sender LocationInView:sender.view]; 7     //Toggle the current playback time of the song 8     self.player.currenttime= (point.x/sender.view.width) *self.player.duration; 9     // Update playback Progress     [self updatecurrenttime];11}

2. Drag the progress bar

Add a drag gesture recognizer first

  

Drag the line toward the controller

  

The code involved:

 1/** 2 * Drag the slider 3 */4-(Ibaction) Panslider: (Uipangesturerecognizer *) Sender {5 6//1. Get moved distance 7 cgpoint t= [Sender TranslationInView:sender.view]; 8//move to clear 9 [sender Settranslation:cgpointzero inview:sender.view];10 11//2. Control slider and progress bar Frame12 Self.sli DER.X+=T.X;13//Set the width of the progress bar self.progressview.width=self.slider.center.x;15 16//3. Set time value CGFloat slid     ERMAXX=SELF.VIEW.WIDTH-SELF.SLIDER.WIDTH;18 double progress=self.slider.x/slidermaxx;19//Current time value = Duration of the music * Current progress value 20 Nstimeinterval time=self.player.duration*progress;21 [self. Slider settitle:[self Strwithtime:time] ForState:UIContr olstatenormal];22 23//4. If you start dragging, stop the timer if (Sender.state==uigesturerecognizerstatebegan) {25//Stop timing device [Self removecurrenttime];27}else if (sender.state==uigesturerecognizerstateended) 28 {29//Set Play  Timer SELF.PLAYER.CURRENTTIME=TIME;31//Turn on timer [self addcurrenttimetimer];33   }34} 

iOS Development Outreach-Audio processing (music player 4)

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.