2021-03-24

簡(jiǎn)單實(shí)現(xiàn)基于IOS的音樂(lè)播放器,并且?guī)в懈柙~,隨播放自動(dòng)滾動(dòng),實(shí)現(xiàn)效果如下:

[圖片上傳失敗...(image-80f7eb-1616574679300)]

首先,需要建立一個(gè)解析歌詞的類(lèi)ZMPlrc,解析歌詞主要就是把時(shí)間和對(duì)應(yīng)的歌詞分離出來(lái),然后存儲(chǔ)到數(shù)組中。

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 /**
時(shí)間
/ @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 ++) { //有兩個(gè)元素,一個(gè)是時(shí)間,一個(gè)是歌詞 NSArray *arr = [sepArray[i] componentsSeparatedByString:@"]"]; //NSLog(@"%@",sepArray[i]); [_timeArray addObject:arr[0]]; [_wordArray addObject:arr[1]]; } //NSLog(@"%@",content); } @end</pre>

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

[圖片上傳失敗...(image-1126e2-1616574679299)]

最后,就可以在控制器中實(shí)現(xiàn)了ZMPViewController,在實(shí)現(xiàn)過(guò)程中,主要就是監(jiān)聽(tīng)音頻播放player的播放時(shí)間,跟之前解析好的每句歌詞對(duì)應(yīng)的時(shí)間進(jìn)行處理。

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>{ //音樂(lè)播放器 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]; //偵聽(tīng)當(dāng)前時(shí)間 [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]; } /
初始化音樂(lè)播放器
*/ - (void)initPlayer{ //后臺(tái)播放音頻設(shè)置 AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; //讓app支持接受遠(yuǎn)程控制事件 [[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; //單曲循環(huán)(負(fù)數(shù)表示單曲循環(huán)) player.numberOfLoops = -1; //速率(默認(rèn)為1) //player.enableRate = YES; //player.rate = 1.0; //總時(shí)間 CGFloat totalSeconds = player.duration; self.totalTimeLabel.text = [NSString stringWithFormat:@"%02d:%02d",(int)totalSeconds / 60, (int)totalSeconds % 60]; //當(dāng)前時(shí)間 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>

需要音樂(lè)在程序進(jìn)入后臺(tái)后同樣能夠播放,那么在plist文件中,增加Required background modes設(shè)置item 0的value為App plays audio or streams audio/video using AirPlay

[圖片上傳失敗...(image-793291-1616574679294)]

并在控制器中,添加后臺(tái)播放音頻的設(shè)置

<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;">//后臺(tái)播放音頻設(shè)置 AVAudioSession *session = [AVAudioSession sharedInstance]; [session setActive:YES error:nil]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; //讓app支持接受遠(yuǎn)程控制事件 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];</pre>

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容