您好,登录后才能下订单哦!
这篇文章主要介绍了iOS如何实现音乐的后台播放,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
实现步骤:
1、首先修改info.plist
2、其次引入两个需要的框架
#import <AVFoundation/AVFoundation.h>#import <MediaPlayer/MediaPlayer.h>
3、设置播放器及后台播放
- (void)viewDidLoad { [super viewDidLoad];// 设置后台播放 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];// 设置播放器 NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"那些花儿" ofType:@"mp3"] ]; _player = [[AVPlayer alloc] initWithURL:url]; [_player play]; _isPlayingNow = YES; //后台播放显示信息设置 [self setPlayingInfo];}#pragma mark - 接收方法的设置- (void)remoteControlReceivedWithEvent:(UIEvent *)event { if (event.type == UIEventTypeRemoteControl) { //判断是否为远程控制 switch (event.subtype) { case UIEventSubtypeRemoteControlPlay: if (!_isPlayingNow) { [_player play]; } _isPlayingNow = !_isPlayingNow; break; case UIEventSubtypeRemoteControlPause: if (_isPlayingNow) { [_player pause]; } _isPlayingNow = !_isPlayingNow; break; case UIEventSubtypeRemoteControlNextTrack: NSLog(@"下一首"); break; case UIEventSubtypeRemoteControlPreviousTrack: NSLog(@"上一首 "); break; default: break; } }}
4、设置后台播放时显示的东西,例如歌曲名字,图片等
- (void)setPlayingInfo {// <MediaPlayer/MediaPlayer.h> MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"pushu.jpg"]]; NSDictionary *dic = @{MPMediaItemPropertyTitle:@"那些花儿", MPMediaItemPropertyArtist:@"朴树", MPMediaItemPropertyArtwork:artWork }; [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dic];}
5、远程控制设置
- (void)viewDidAppear:(BOOL)animated {// 接受远程控制 [self becomeFirstResponder]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];}- (void)viewDidDisappear:(BOOL)animated {// 取消远程控制 [self resignFirstResponder]; [[UIApplication sharedApplication] endReceivingRemoteControlEvents];}
感谢你能够认真阅读完这篇文章,希望小编分享的“iOS如何实现音乐的后台播放”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。