IOS music player (automatically scrolling lyrics) and ios music player

Source: Internet
Author: User

IOS music player (automatically scrolling lyrics) and ios music player

A simple IOS-based music player with lyrics that automatically scroll along with playback. The effect is as follows:



First, you need to create a class ZMPlrc for parsing the lyrics. The main function of parsing the lyrics is to separate the time from the corresponding lyrics and store them in the array.

ZMPlrc. h

# Import <Foundation/Foundation. h> @ interface ZMPlrc: NSObject/** time */@ property (nonatomic, strong) NSMutableArray * timeArray;/** lyrics */@ property (nonatomic, strong) NSMutableArray * wordArray;/** parse the lyrics */-(void) parselrc; @ end

ZMPlrc. m

# Import "ZMPlrc. h "@ implementation ZMPlrc-(instancetype) init {self = [super init]; if (self) {_ timeArray = [NSMutableArray array]; _ wordArray = [NSMutableArray array];} return self;}/** lyrics */-(NSString *) getLrcPath {return [[NSBundle mainBundle] pathForResource: @ "Liang jingru-even shower" ofType: @ "lrc"];}/** resolution lyrics */-(void) parselrc {NSString * content = [NSString stringWithContentsOfFile: [self getLrcPath] encoding: NSUTF8StringEncoding error: nil]; NSArray * sepArray = [content componentsSeparatedByString: @ "["]; for (int I = 5; I <sepArray. count; I ++) {// There are two elements: time and arr = [sepArray [I] componentsSeparatedByString: @ "]; // NSLog (@ "% @", sepArray [I]); [_ timeArray addObject: arr [0]; [_ wordArray addObject: arr [1];} // NSLog (@ "% @", content) ;}@ end


Then, add the necessary controls to the storyboard.



Finally, ZMPViewController can be implemented in the Controller. in the implementation process, it is mainly to listen to the playing time of the audio player and process the time corresponding to each previously parsed lyrics.

ZMPViewController. h

#import <UIKit/UIKit.h>@interface ZMPViewController : UIViewController@property (weak, nonatomic) IBOutlet UITableView *lrcTableView;@property (weak, nonatomic) IBOutlet UISlider *timeSlider;@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;@property (weak, nonatomic) IBOutlet UIButton *lastMusicBtnClick;- (IBAction)playBtnClick:(UIButton *)sender;- (IBAction)preMusicBtnClick:(id)sender;- (IBAction)valueChange:(UISlider *)sender;- (IBAction)nextMusicBtnClick:(id)sender;@end

ZMPViewController. m

# Import "ZMPViewController. h "# import <AVFoundation/AVFoundation. h> # import "ZMPlrc. h "@ interface ZMPViewController () <UITableViewDataSource, UITableViewDelegate> {// music player AVAudioPlayer * player; ZMPlrc * lrc; NSInteger currentRow;} @ end @ implementation ZMPViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self initPlayer]; // listens when Previous time [nst1_scheduledtimerwithtimeinterval: 0.5 target: self selector: @ selector (updateTime) userInfo: nil repeats: YES]; lrc = [[ZMPlrc alloc] init]; [lrc parselrc]; [self. lrcTableView registerClass: [UITableViewCell class] forCellReuseIdentifier: @ "CELL"]; [self. lrcTableView reloadData];}-(void) updateTime {CGFloat currentTime = player. currentTime; // self. currentTimeLabel. text = [NSString stringWith Format: @ "% 02d: % 02d", (int) currentTime/60, (int) currentTime % 60]; self. timeSlider. value = currentTime/player. duration; for (int I = 0; I <lrc. timeArray. count; I ++) {NSArray * arr = [lrc. timeArray [I] componentsSeparatedByString: @ ":"]; CGFloat compTime = [arr [0] integerValue] * 60 + [arr [1] floatValue]; if (player. currentTime> compTime) {currentRow = I;} else {break;} [self. lrcTableView re LoadData]; [self. lrcTableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow: currentRow inSection: 0] atScrollPosition: UITableViewScrollPositionMiddle animated: YES];}/** initialize the music player */-(void) initPlayer {// set AVAudioSession * session = [AVAudioSession sharedInstance]; [session setActive: YES error: nil]; [session setCategory: AVAudioSessionCategoryPlayback error: nil]; // allow the app to support remote control events [[UIAppli Cation sharedApplication] beginReceivingRemoteControlEvents]; NSString * path = [[NSBundle mainBundle] pathForResource: @ "Liang jinru-even shower" ofType: @ "mp3"]; NSURL * url = [NSURL fileURLWithPath: path]; player = [[AVAudioPlayer alloc] initWithContentsOfURL: url error: nil]; // audio channel-1 ------ left audio, 1 ----- right audio player. pan = 0; // volume: 0 ~ 1 player. volume = 1; // single loop (negative number indicates single loop) player. numberOfLoops =-1; // rate (1 by default) // player. enableRate = YES; // player. rate = 1.0; // total time CGFloat totalSeconds = player. duration; self. totalTimeLabel. text = [NSString stringWithFormat: @ "% 02d: % 02d", (int) totalSeconds/60, (int) totalSeconds % 60]; // The current time player. currentTime; # if 0 // play [player play]; // stop [player stop]; // pause [player pause]; # endif}-(void) didRec EiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated.}-(IBAction) playBtnClick :( UIButton *) sender {sender. selected =! Sender. selected; if (sender. selected) {[player prepareToPlay]; [player play];} else {[player pause] ;}}-(IBAction) preMusicBtnClick :( id) sender {[self initPlayer];} -(IBAction) valueChange :( UISlider *) sender {player. currentTime = player. duration * sender. value;}-(IBAction) nextMusicBtnClick :( id) sender {[self initPlayer];} # pragma mark-TableViewDelegate-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return lrc. wordArray. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {UITableViewCell * cell = [tableView progress: @ "CELL"]; if (indexPath. row = currentRow) {cell. textLabel. textColor = [UIColor redColor];} else {cell. textLabel. textColor = [UIColor blackColor];} cell. textLabel. textAlignment = NSTextAlignmentCenter; cell. textLabel. font = [UIFont systemFontOfSize: 15]; cell. textLabel. text = lrc. wordArray [indexPath. row]; return cell;} @ end

If you want to play the music after the program enters the background, add Required background modes in the plist file and set the value of item 0 to App plays audio or streams audio/video using AirPlay.


Add the background audio playing settings in the controller.

// Set AVAudioSession * session = [AVAudioSession sharedInstance]; [session setActive: YES error: nil]; [session setCategory: AVAudioSessionCategoryPlayback error: nil]; // enable the app to support remote control events [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

In addition, you can leave a message if you need a Demo.

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.