AVPlayer之音乐播放

今天来整理一下以前自己学到的AVPlayer播放音乐的功能,这虽然简单,但是温故而知新嘛!下面说说做一个简单播放界面的思路和核心代码.

1.创建单例类MusicManager,模型类Music,音乐控制器MusicViewController, 和一个MusictableViewController

2.在单例中声明单例和获取数据,初始化模型数组

3.在表示图控制器中引入单例拿到数据:[[MusicManager shareInstance] getData];//这是单例中获取数据的方法

4.在表视图中显示数据

5.从表视图跳转到MusicViewController的方式:首先需要在故事版中将控制器和MusicViewController相关联,再设置storyboadID:

1):在点击cell的方法中 通过表视图的故事版实例化MusicViewController 然后模态或者push过去

MusicViewController *musicVC = [self.storyboard instantiateViewControllerWithIdentifier:@"storyboadID"];

2:通过从表视图的cell连线到MusicViewController上, 然后在表视图的下面方法中跳转:需要设置segue的标示符

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

   if ([segue.identifier isEqualToString:@"标示符"]) {

  //因为连线的是cell,所以这里sender表示的是cell

  MusicViewController *musicVC = segue.destinationViewController;

  UITableViewCell *cell = (UITableViewCell *)sender;

  NSIndexPath *indexPath = [self.tableView indexPathForCell:cell ];

  //这里playIndexPath是MusicViewController中的属性 ,表示当前播放音乐的位置信息

  musicVC.playIndexPath = indexPath;

  }

}

6.现在来完善MusicViewController中的代码:

1):通过单例来获取数据,再赋值,然后写播放音乐的代码

    Music *music = [MusicManager shareInstance].dataArray[self.indexpath.row];

NSUrl *url = [NSUrl fillUrlWithPath:[NSBundle mainBundle] pathForResource:music.name ofType:@"mp3"];

AVPlayerItem  *item = [[AVPlayerItem alloc] initWithUrl:url];

 [MusicManager shareInstance].player = [[AVPlayer alloc] initWithPlayerItem:item];

 [[MusicManager shareInstance] play];

2):创建计时器,监控slider的值变化

在计时器方法中有两个重要的地方:计算音乐的总时间和当前时间 单位是seconds秒

//计算总时间 value / timescale, AVPayerItm中包含了音乐的时间各种各样的信息

 long long int totalTime = [MusicManager shareInstance].player.currentItem.duration.value /  [MusicManager shareInstance].player.currentItem.duration.timescale];

//计算当前时间

long long int currentTime =  [MusicManager shareInstance].player.currentTime.value /  [MusicManager shareInstance].player.currentTime.timescale;

3):拖动进度条改变音乐当前播放的时间

CMTime time = [MusicManager shareInstance].player.currentTime;

time.value = self.slider.value * time.timescale;

 [[MusicManager shareInstance].player seekToTime:time];

4):暂停播放按钮

判断是否在播放:[MusicManager shareInstance].player.rate = 1.0;

5):下一首按钮:

_playIndex++;//这是声明的属性, 在viewDidLoad中已经被赋值 _playInex = self.indexPath.row;

if (_playIndex == [MusicManager shareInstance].dataArray.count) {

  _playIndex = 0;

}

//然后开始获取歌曲信息并且将现在的item替换掉

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[[MusicManager shareInstance].dataArray[_playindex] name] ofType:@"mp3"]];

    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];

[[MusicManager shareInstance].player replaceCurrentItemWithPlayItem:item];

//然后再重新对界面显示的歌曲等赋值

6):上一首按钮和下一首中的代码相差不大:

if (_playIndex == -1) {

  _playIndex = [MusicManager shareInstance].dataArray.count - 1;

}

7):控制声音的slider

[MusicManager shareInstance].player.volume = self.timeSlider.value;

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/arenouba/p/5294447.html