iOS Development Outreach-Audio processing (music player 3)

Source: Internet
Author: User
Tags file url

iOS Development Outreach-Audio processing (music player 3)

Description: This article focuses on the encapsulation of audio tool classes and playback tools classes.

One, data transfer between controllers

1. Transfer of data between two controllers the first method: Self.parentviewcontroller.music=self.music[indexpath.row]; the second approach is not satisfied: Pass the entire array to it the third way: set a data source , set the data source for the playback controller to be the controller. self.parentviewcontroller.datasource=self; Benefits: no coupling, any implementation of the protocol can be used as a data source. The fourth approach: the use of the entire project will be used to the audio resources to a tool class to manage, so it is not passed. You can ask for resources directly from the tool class. Ii. Encapsulation of an audio tool classCreate a new audio tool class for managing music data (music model) The code in the tool class is designed as follows: YYMusicTool.h file
1//2//  YYMusicTool.h 3//4  5 #import <Foundation/Foundation.h> 6 @class yymusicmodel; 7 @interface Yymus Ictool:nsobject 8/** 9  *  return all the songs of  */11 + (Nsarray *) musics;12 x/**14  *  return the song being played on the  */16 + (Y Ymusicmodel *) playingmusic;17 + (void) Setplayingmusic: (Yymusicmodel *) playingmusic;18/**20  *  next song 21  */22 + (Yymusicmodel *) nextmusic;23/**25  *  Previous song */27  + (Yymusicmodel *) previousmusic;28 @ End

YYMUSICTOOL.M file

 1//2//YYMUSICTOOL.M 3//4 5 #import "YYMusicTool.h" 6 #import "YYMusicModel.h" 7 #import "MJExtension.h" 8 9 @imp Lementation YYMusicTool10 one static nsarray *_musics;12 static Yymusicmodel *_playingmusic;13 (/**15) * @return back all the songs Qu */17 + (Nsarray *) musics18 {_musics==nil) {_musics=[yymusicmodel objectarraywithfilename:@ "music      S.plist "];21}22 return _musics;23}24 + (void) Setplayingmusic: (Yymusicmodel *) playingMusic26 {27/*28 * If there are no songs to play, or if the song name is not in the music library, then return directly 29 if the song you want to play is the one that is currently playing, then return directly to the */31 if (!playingmusic | |![ [Self musics]containsobject:playingmusic]) return;32 if (_playingmusic = = playingmusic) return;33 _PLAYINGMUSIC=PL   AYINGMUSIC;34}35/**36 * Returns the song that is being played */38 + (Yymusicmodel *) playingMusic39 {43 return _playingmusic;41}42/**44         * Next song */46 + (Yymusicmodel *) nextMusic47 {48//set an initial value of 51 int nextindex = 0;50 if (_playingmusic) { Gets the index of the currently playing music. Playingindex = [Self musics] indexofobject:_playingmusic];53//Set index of next music nextindex = Playingindex+1;5         5//check array out of bounds, if the next music is the last, then reset to 056 if (nextindex>=[self musics].count) {nextindex=0;58 }59}60 return [self musics][nextindex];61}62 63/**64 * Previous song + */66 + (Yymusicmodel *) previousMusic67 {6 8//Set an initial value of previousindex int = 0;70 if (_playingmusic) {71//Gets the index of the currently playing music. Int Playingindex         = [[Self musics] indexofobject:_playingmusic];73//Set index of next music previousindex = playingindex-1;75         Check the array out of bounds, if the next music is the last, then reset to 076 if (previousindex<0) {previousindex=[self musics].count-1;78 }79}80 return [self musics][previousindex];81}82 @end

Third, packaging a music playback tool class

The code in the tool class is designed as follows:

YYAudioTool.h file

1//2//  YYAudioTool.h 3//4  5 #import <Foundation/Foundation.h> 6 #import <avfoundation/avfoundation. H> 7 @interface yyaudiotool:nsobject 8/** 9  * Play music file  */11 + (BOOL) Playmusic: (NSString *) filename;12/**13
   * Pause Play  */15 + (void) Pausemusic: (NSString *) filename;16/**17  * Play music file  + */19 + (void) Stopmusic: ( NSString *) filename;20/**22  * Play audio file  */24 + (void) PlaySound: (NSString *) filename;25/**26  * Destroy Sound 27  */28 + (void) Disposesound: (NSString *) filename;29 @end

YYAUDIOTOOL.M file

  1//2//YYAUDIOTOOL.M 3//4 5 #import "YYAudioTool.h" 6 7 @implementation Yyaudiotool 8/** 9 * Store All Music players Ten */one static nsmutabledictionary *_musicplayers; + (Nsmutabledictionary *) musicplayers (_musicplayers==nil) {_musicplayers=[nsmutabledictionar Y dictionary]; (+)-return _musicplayers; 18} 19 20/** 21 * Storage of all sound IDs * * * static nsmutabledictionary *_soundids; + (Nsmutabledictionary *) Soundids {+ if (_soundids==nil) {_soundids=[nsmutabledictionary dictionary ]; _soundids return; 30} 31 32 33/** 34 * Play Music * */+ (BOOL) Playmusic: (NSString *) filename (!filename) return no;//if not transmitted Enter the file name, then directly return 39//1. Remove the corresponding player Avaudioplayer *player=[self musicplayers][filename]; 41 42//2. If the player is not created, initialize the URL of the!player {44//2.1 audio file Nsurl *url=[[nsbundle main Bundle]urlforresource:filename Withextension:nil]; if (!url) reTurn no;//if the URL is empty, then return directly 47 48//2.2 create player Player=[[avaudioplayer alloc]initwithcontentsofurl:u RL Error:nil]; 50 51//2.3 Buffered if (![ Player Preparetoplay]) return no;//If the buffer fails, then return directly to 53 54//2.4 in the Dictionary [self musicplayers][filename ]=player; 56} 57 58//3. Play if (![ Player IsPlaying]) {60//if it is not currently playing, then play the [player play], and the return yes;//is playing      , then return yes to + (void) Pausemusic: (NSString *) filename (!filename) return;//If no file name is passed in, then return 70 directly 71//1. Remove the corresponding player Avaudioplayer *player=[self musicplayers][filename]; 73 74//2. Pause [player pause];//] If the palyer is empty, that's equivalent to [nil pause], so there's no need to do it here. * + + (void) Stopmusic: (NSS Tring *) filename (!filename) return;//If the file name is not passed in, it returns 82 83//1 directly. Remove the corresponding player. Avaudioplayer *p Layer=[self Musicplayers][filename]; 85 86//2. Stop [PLAYer stop]; 88 89//3 Remove the player from the dictionary [[self musicplayers] removeobjectforkey:filename]; 91} 92 93//Play sound 94 + (void) PlaySound: (NSString *) filename (!filename) return, 97//1. Remove the corresponding sound effects 98 S Ystemsoundid soundid=[[self Soundids][filename] unsignedintegervalue]; 99 100//2. Play Sound 101//2.1 If the sound ID does not exist, create the URL105 NS of the 102 if (!soundid) {103 104//audio file URL *url=[[nsbundle mainbundle]urlforresource:filename withextension:nil];106 if (!url) return;//if the URL does not exist, then return directly 1         108 Osstatus status = Audioservicescreatesystemsoundid ((__bridge cfurlref) (URL), &soundid); 109     NSLog (@ "%ld", status); 110//Deposit into the dictionary 111 [self soundids][filename][email protected] (soundid); 112 }113 114//2.2 with sound ID, play the sound effects on the Audioservicesplaysystemsound (Soundid); 116}117 118//Destroy Sound effects 119 + (void) Disposesound:    (NSString *) filename120 {121//If the incoming file name is empty, then return directly to 122 if (!filename) return;123 124 1. Remove the corresponding sound effects systemsoundid soundid=[[self Soundids][filename] unsignedintegervalue];126 127//2. Destroy F (soundid) {129 audioservicesdisposesystemsoundid (SOUNDID); 130 131//2.1 Remove the section from the dictionary after it is destroyed [[s Elf soundids]removeobjectforkey:filename];133}134}135 @end

Iv. code handling in the music playback controller

YYPLAYINGVIEWCONTROLLER.M file

  1//2//YYPLAYINGVIEWCONTROLLER.M 3//4 5 #import "YYPlayingViewController.h" 6 #import "YYMusicTool.h" 7 #im Port "YYMusicModel.h" 8 #import "YYAudioTool.h" 9 @interface Yyplayingviewcontroller () @property (weak, Nonatomi c) Iboutlet Uiimageview *iconview; @property (Weak, nonatomic) Iboutlet UILabel *songlabel; @property (Weak, nonatomic) Iboutlet UILabel *singerlabel; @property (Weak, nonatomic) Iboutlet UILabel *durationlabel; @property (Nonatomic,strong) Yymusicmodel *playingmusic; -(ibaction) exit; @end @implementation Yyplayingviewcontroller #pragma mark-public Method-(void) Show 23 {24//1. Disable the entire app click Pieces of UIWindow *window=[uiapplication Sharedapplication].keywindow; Window.userinteractionenabled=no; 27 28//2. Add the Playback interface 29//Set the view size to cover the entire window of the self.view.frame=window.bounds; 31//Set view display self.view.hidden=no; 33//Add view to the window. [Window AddSubview:self.view]; 35 36//3. Detect if the song has changed PNS if (Self.playingmusic!=[yymusictool Playingmusic]) {[self rresetplayingmusic]; 39} 40 41 4. Use the animation to show the view self.view.y=self.view.height;          [UIView animatewithduration:0.25 animations:^{self.view.y=0; completion:^ (BOOL finished) {46 47//Set music data to [self starplayingmusic]; Window.userinteractionenabled=yes; 50}]; #pragma mark-Private Method 53//Reset the music being played Rresetplayingmusic 55 {56//1. Reset Interface Data Self.iconview.image=[u IImage imagenamed:@ "PLAY_COVER_PIC_BG"]; Self.songlabel.text=nil; Self.singerlabel.text=nil; 60 61//2. Stop playing [Yyaudiotool StopMusic:self.playingMusic.filename]; 63} 64//Start playing music data-(void) Starplayingmusic 66 {67//1. Set interface Data 68 69//Remove music currently playing//Yymusicmodel *p Layingmusic=[yymusictool Playingmusic]; 71 72//If the currently playing music is the incoming music, then return directly to the Self.playingmusic==[yymusictool Playingmusic] return; 74//Access music self.playingmusic=[yymusictool Playingmusic]; Self.iconview.image=[uiimage ImageNamed:self.playingMusic.icon]; Self.songlabel.text=self.playingmusic.name; Self.singerlabel.text=self.playingmusic.singer; 79 80//2. Start playing Bayi [Yyaudiotool PlayMusic:self.playingMusic.filename]; The 86//Back button mark--(ibaction) exit {88//1. Disable click events for the entire app UIWindow *window =[uiapplication Sharedapplication].keywindow; Window.userinteractionenabled=no;      91 92//2. Animated Hide View [UIView animatewithduration:0.25 animations:^{94 self.view.y=window.height; 95         } completion:^ (BOOL finished) {Window.userinteractionenabled=yes; 97//Set view hide to save some performance 98 Self.view.hidden=yes; }];100}101 @end

Note: First let the user see everything on the interface before starting to play the song.

Tip: The general player needs to do a reset. When you switch from one song to another, you should delete the previous piece of information, so before the show animation, you should detect if you have changed the song, and if you change the song, you should do a reset operation.

Achieve the effect (can smoothly switch and play songs, the following is the interface display):

Five, supplementary code

YYMUSICSVIEWCONTROLLER.M file

 1//2//YYMUSICSVIEWCONTROLLER.M 3//4 5 #import "YYMusicsViewController.h" 6 #import "YYMusicModel.h" 7 #import "MJ Extension.h "8 #import" YYMusicCell.h "9 #import" YYPlayingViewController.h "Ten #import" YYMusicTool.h "@interface YY Musicsviewcontroller () @property (nonatomic,strong) yyplayingviewcontroller *playingviewcontroller;15 @end16 17 @     Implementation YYMusicsViewController18 #pragma mark-lazy load-(Yyplayingviewcontroller *) PlayingViewController21 {22     if (_playingviewcontroller==nil) {_playingviewcontroller=[[yyplayingviewcontroller alloc]init];24}25 Return _playingviewcontroller;26}27-(void) viewDidLoad29 {[Super viewdidload];31}32 #pragma mark-table v Iew Data source34/**35 * Altogether how many groups of */37-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableView38 {$ return 1;40}41/**42 * Number of rows per group */44-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) Section45 {return [Yymusictool Musics].count;47}48/**49 * cell50 */51 per row (UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath :(Nsindexpath *) indexPath52 {Yymusiccell *cell=[yymusiccell cellwithtableview:tableview];54 cell.music=[yymusic Tool musics][indexpath.row];55 return cell;56}57/**58 * Set height per cell */60-(CGFloat) TableView: (UITableView *) tab Leview Heightforrowatindexpath: (Nsindexpath *) indexPath61 {70;63 return}64/**66 * * Cell's Click event */68-(void) t Ableview: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexPath69 {70//1. Uncheck the line that was clicked [Tablevi EW Deselectrowatindexpath:indexpath animated:yes];72 73//2. Set the song that is playing [Yymusictool setplayingmusic:[yymusict    Ool musics][indexpath.row]];75 76//Call public method [Self.playingviewcontroller show];78 79////Execute Segue Jump 80// [Self performseguewithidentifier:@ "music2playing" sender:nil];81}82 @end

iOS Development Outreach-Audio processing (music player 3)

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.