2021-03-24

简单实现基于IOS的音乐播放器,并且带有歌词,随播放自动滚动,实现效果如下:

[图片上传失败...(image-80f7eb-1616574679300)]

首先,需要建立一个解析歌词的类ZMPlrc,解析歌词主要就是把时间和对应的歌词分离出来,然后存储到数组中。

ZMPlrc.h

<pre name="code" class="objc prettyprint prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 10px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; overflow-wrap: break-word; background-color: rgb(247, 247, 249); border: none; border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#import <Foundation/Foundation.h> @interface ZMPlrc : NSObject /**
时间
/ @property (nonatomic,strong)NSMutableArray timeArray; /
歌词
/ @property (nonatomic,strong)NSMutableArray wordArray; /
解析歌词
*/ - (void)parselrc; @end</pre>

ZMPlrc.m

<pre name="code" class="objc prettyprint prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 10px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; overflow-wrap: break-word; background-color: rgb(247, 247, 249); border: none; border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#import "ZMPlrc.h" @implementation ZMPlrc - (instancetype)init { self = [super init]; if (self) { _timeArray = [NSMutableArray array]; _wordArray = [NSMutableArray array]; } return self; } /**
歌词路径
/ - (NSString )getLrcPath{ return [[NSBundle mainBundle] pathForResource:@"梁静茹-偶阵雨" ofType:@"lrc"]; } /
解析歌词
*/ - (void)parselrc{ NSString *content = [NSString stringWithContentsOfFile:[self getLrcPath] encoding:NSUTF8StringEncoding error:nil]; NSArray *sepArray = [content componentsSeparatedByString:@"["]; for (int i = 5; i < sepArray.count; i ++) { //有两个元素,一个是时间,一个是歌词 NSArray *arr = [sepArray[i] componentsSeparatedByString:@"]"]; //NSLog(@"%@",sepArray[i]); [_timeArray addObject:arr[0]]; [_wordArray addObject:arr[1]]; } //NSLog(@"%@",content); } @end</pre>

接着,在storyboard中添加必要的控件。

[图片上传失败...(image-1126e2-1616574679299)]

最后,就可以在控制器中实现了ZMPViewController,在实现过程中,主要就是监听音频播放player的播放时间,跟之前解析好的每句歌词对应的时间进行处理。

ZMPViewController.h

<pre name="code" class="objc prettyprint prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 10px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; overflow-wrap: break-word; background-color: rgb(247, 247, 249); border: none; border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#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</pre>

ZMPViewController.m

<pre name="code" class="objc prettyprint prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 10px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; overflow-wrap: break-word; background-color: rgb(247, 247, 249); border: none; border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#import "ZMPViewController.h" #import <AVFoundation/AVFoundation.h> #import "ZMPlrc.h" @interface ZMPViewController ()<UITableViewDataSource,UITableViewDelegate>{ //音乐播放器 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]; //侦听当前时间 [NSTimer 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 stringWithFormat:@"%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 reloadData]; [self.lrcTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; } /
初始化音乐播放器
*/ - (void)initPlayer{ //后台播放音频设置 AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; //让app支持接受远程控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; NSString *path = [[NSBundle mainBundle] pathForResource:@"梁静茹-偶阵雨" ofType:@"mp3"]; NSURL *url = [NSURL fileURLWithPath:path]; player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; //声道 -1------左声道,1-----右声道 player.pan = 0; //音量:0~1 player.volume = 1; //单曲循环(负数表示单曲循环) player.numberOfLoops = -1; //速率(默认为1) //player.enableRate = YES; //player.rate = 1.0; //总时间 CGFloat totalSeconds = player.duration; self.totalTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)totalSeconds / 60, (int)totalSeconds % 60]; //当前时间 player.currentTime; #if 0 //播放 [player play]; //停止 [player stop]; //暂停 [player pause]; #endif } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // 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 dequeueReusableCellWithIdentifier:@"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</pre>

需要音乐在程序进入后台后同样能够播放,那么在plist文件中,增加Required background modes设置item 0的value为App plays audio or streams audio/video using AirPlay

[图片上传失败...(image-793291-1616574679294)]

并在控制器中,添加后台播放音频的设置

<pre name="code" class="objc prettyprint prettyprinted" style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px; display: block; padding: 10px; margin: 0px 0px 10px; line-height: 1.42857; color: rgb(51, 51, 51); word-break: break-all; overflow-wrap: break-word; background-color: rgb(247, 247, 249); border: none; border-radius: 4px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">//后台播放音频设置 AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; //让app支持接受远程控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];</pre>

另外,需要Demo的可以留言。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,706评论 4 366
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,002评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,462评论 0 250
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,375评论 0 216
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,763评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,849评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,033评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,768评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,490评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,734评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,204评论 1 264
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,566评论 3 260
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,227评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,137评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,934评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,926评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,774评论 2 274

推荐阅读更多精彩内容