IOS 播放音频流媒体
#pragma mark - 加载播放数据
- (void)loadData:(NSString *)musicUrl
{
NSURL *playURL = [NSURL URLWithString:musicUrl];
self.playerItem = [AVPlayerItem playerItemWithURL:playURL];
//创建单利对象
self.playStationDetailsManager = [StationDetailsManager defaultManager];
[_playStationDetailsManager.avPlayer replaceCurrentItemWithPlayerItem:self.playerItem];
[self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];//监听status属性
//添加音乐播放结束通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
//进入就播放
[_playStationDetailsManager.avPlayer play];
}
#pragma mark 设置监听歌曲的方法,并进行页面赋值
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
AVPlayerItem *playerItem = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"status"]) {
//准备播放
if ([playerItem status] == AVPlayerStatusReadyToPlay) {
CMTime duration = self.playerItem.duration;//获取MP3的总长度
self.playView.planSlider.maximumValue = CMTimeGetSeconds(duration);//设置滑竿的最大值
NSLog(@"%f",CMTimeGetSeconds(duration));
[self monitoringPlayback:self.playerItem];//监听播放的状态
}else if ([playerItem status] == AVPlayerStatusFailed){
//加载失败
NSLog(@"加载失败");
}
}
}