对添加监听
- (void)addStreamerObserver {
[_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
[_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
[_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
}
/// 播放器销毁
- (void)dealloc{
if (_streamer !=nil) {
[_streamer pause];
[_streamer removeObserver:self forKeyPath:@"status" context:kStatusKVOKey];
[_streamer removeObserver:self forKeyPath:@"duration" context:kDurationKVOKey];
[_streamer removeObserver:self forKeyPath:@"bufferingRatio" context:kBufferingRatioKVOKey];
_streamer =nil;
}
}
- (void)removeStreamerObserver {
[_streamer removeObserver:self forKeyPath:@"status"];
[_streamer removeObserver:self forKeyPath:@"duration"];
[_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == kStatusKVOKey) {
[self performSelector:@selector(updateStatus)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
} else if (context == kDurationKVOKey) {
[self performSelector:@selector(updateSliderValue:)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
} else if (context == kBufferingRatioKVOKey) {
[self performSelector:@selector(updateBufferingStatus)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)updateSliderValue:(id)timer {
}
-(void)updateBufferingStatus
{
}
- (void)updateStatus {
//self.musicIsPlaying = NO;
_musicIndicator.state = NAKPlaybackIndicatorViewStateStopped;
switch ([_streamer status]) {
case DOUAudioStreamerPlaying:
// self.musicIsPlaying = YES;
_musicIndicator.state = NAKPlaybackIndicatorViewStatePlaying;
break;
case DOUAudioStreamerPaused:
break;
case DOUAudioStreamerIdle:
break;
case DOUAudioStreamerFinished:
break;
case DOUAudioStreamerBuffering:
_musicIndicator.state = NAKPlaybackIndicatorViewStatePlaying;
break;
case DOUAudioStreamerError:
break;
}
}
这样就能播放了。
锁屏时的音乐显示、拔出耳机后暂停播放、监听音频打断事件
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//接受远程控制
[self becomeFirstResponder];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
//这个不能忘记了
-(BOOL)canBecomeFirstResponder{
return YES;
}
- (void)viewDidLoad {
[super viewDidLoad];
//音乐播放器
[self initPlayer];
}
#pragma mark =========================音乐播放==============================
//音乐播放器
-(void)initPlayer
{
_audioTrack = [[Track alloc] init];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//让app支持接受远程控制事件
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//添加通知,拔出耳机后暂停播放
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];
// 监听音频打断事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionWasInterrupted:) name:AVAudioSessionInterruptionNotification object:session];
}
// 监听音频打断事件
- (void)audioSessionWasInterrupted:(NSNotification *)notification
{
//被打断时
if (AVAudioSessionInterruptionTypeBegan == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
[_streamer pause];
UIButton *btn = (UIButton *)[self.view viewWithTag:2000];
[btn setBackgroundImage:[UIImage imageNamed:@"music_stop_icon"] forState:UIControlStateNormal];
}
else if (AVAudioSessionInterruptionTypeEnded == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
}
}
// 拔出耳机后暂停播放
-(void)routeChange:(NSNotification *)notification{
NSDictionary *dic=notification.userInfo;
int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];
//等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];
AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];
//原设备为耳机则暂停
if ([portDescription.portType isEqualToString:@"Headphones"]) {
[_streamer pause];
UIButton *btn = (UIButton *)[self.view viewWithTag:2000];
[btn setBackgroundImage:[UIImage imageNamed:@"music_stop_icon"] forState:UIControlStateNormal];
}
}
}
//锁屏时音乐显示(这个方法可以在点击播放时,调用传值)
- (void)setupLockScreenInfoWithSing:(NSString *)sign WithSigner:(NSString *)signer WithImage:(UIImage *)image
{
// 1.获取锁屏中心
MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
//初始化一个存放音乐信息的字典
NSMutableDictionary *playingInfoDict = [NSMutableDictionary dictionary];
// 2、设置歌曲名
if (sign) {
[playingInfoDict setObject:sign forKey:MPMediaItemPropertyAlbumTitle];
}
// 设置歌手名
if (signer) {
[playingInfoDict setObject:signer forKey:MPMediaItemPropertyArtist];
}
// 3设置封面的图片
//UIImage *image = [self getMusicImageWithMusicId:self.currentModel];
if (image) {
MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
[playingInfoDict setObject:artwork forKey:MPMediaItemPropertyArtwork];
}
// 4设置歌曲的总时长
//[playingInfoDict setObject:self.currentModel.detailDuration forKey:MPMediaItemPropertyPlaybackDuration];
//音乐信息赋值给获取锁屏中心的nowPlayingInfo属性
playingInfoCenter.nowPlayingInfo = playingInfoDict;
// 5.开启远程交互
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
//锁屏时操作
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
UIButton *sender = (UIButton *)[self.view viewWithTag:2000];
switch (receivedEvent.subtype) {//判断是否为远程控制
case UIEventSubtypeRemoteControlPause:
[[HYNEntertainmentController sharedInstance].streamer pause];
[sender setBackgroundImage:[UIImage imageNamed:@"music_stop_icon"] forState:UIControlStateNormal];
break;
case UIEventSubtypeRemoteControlStop:
break;
case UIEventSubtypeRemoteControlPlay:
[[HYNEntertainmentController sharedInstance].streamer play];
[sender setBackgroundImage:[UIImage imageNamed:@"music_play_icon"] forState:UIControlStateNormal];
break;
case UIEventSubtypeRemoteControlTogglePlayPause:
break;
case UIEventSubtypeRemoteControlNextTrack:
break;
case UIEventSubtypeRemoteControlPreviousTrack:
break;
default:
break;
}
}
}










