播放后台音频

摘要:
1.后台模式播放1#import 2#导入 3#导入45@interfaceViewController:UIViewController67@property(弱,不

1、申明后台模式播放

播放后台音频第1张

1 #import <UIKit/UIKit.h>
2 #import <AVFoundation/AVFoundation.h>
3 #import <MediaPlayer/MediaPlayer.h>
4 
5 @interface ViewController : UIViewController<MPMediaPickerControllerDelegate>
6 
7 @property (weak, nonatomic) IBOutlet UIButton *playButton;
8 @property (weak, nonatomic) IBOutlet UILabel *infoLabel;
9 @property (weak, nonatomic) IBOutlet UIImageView *artworkImageView;
10 @property (nonatomic, strong) AVAudioSession *session;
11 @property (nonatomic, strong) AVPlayer *player;
12 @property (nonatomic, strong) NSMutableArray *playlist;
13 @property (nonatomic)NSInteger currentIndex;
14 
15 - (IBAction)goToPrevTrack:(id)sender;
16 - (IBAction)goToNextTrack:(id)sender;
17 - (IBAction)togglePlay:(id)sender;
18 - (IBAction)queueFromLibrary:(id)sender;
19 - (IBAction)clearPlaylist:(id)sender;
20 
21 @end
1 #import "ViewController.h"
2 
3 @interfaceViewController ()
4 
5 @end
6 
7 @implementationViewController
8 @synthesizeplayButton;
9 @synthesizeinfoLabel;
10 @synthesizeartworkImageView;
11 
12 - (void)viewDidLoad
13 {
14 [super viewDidLoad];
15 
16     self.session =[AVAudioSession sharedInstance];
17     NSError *error;
18     //申明后台模式播放
19     [self.session setCategory:AVAudioSessionCategoryPlayback error:&error];
20     if(error)
21 {
22         NSLog(@"Error setting audio session category: %@", error);
23 }
24     [self.session setActive:YES error:&error];
25     if(error)
26 {
27         NSLog(@"Error activating audio session: %@", error);
28 }
29     
30     self.playlist =[[NSMutableArray alloc] init];
31     self.player =[[AVPlayer alloc] init];
32 }
33 
34 - (void)didReceiveMemoryWarning
35 {
36 [super didReceiveMemoryWarning];
37     //Dispose of any resources that can be recreated.
38 }
39 
40 -(void)updateNowPlaying
41 {
42     if (self.player.currentItem !=nil)
43 {
44         MPMediaItem *currentMPItem =[self.playlist objectAtIndex:self.currentIndex];
45         
46         self.infoLabel.text = [NSString stringWithFormat:@"%@ - %@", [currentMPItem valueForProperty:MPMediaItemPropertyTitle],  [currentMPItem valueForProperty:MPMediaItemPropertyArtist]];
47         
48         UIImage *artwork =[[currentMPItem valueForProperty:MPMediaItemPropertyArtwork] imageWithSize:self.artworkImageView.frame.size];
49         self.artworkImageView.image =artwork;
50         
51         if ([MPNowPlayingInfoCenter class])
52 {
53             NSString *title =[currentMPItem valueForProperty:MPMediaItemPropertyTitle];
54             NSString *artist =[currentMPItem valueForProperty:MPMediaItemPropertyArtist];
55             NSString *album =[currentMPItem valueForProperty:MPMediaItemPropertyAlbumTitle];
56             
57             NSDictionary *mediaInfo =[NSDictionary dictionaryWithObjectsAndKeys:
58 artist, MPMediaItemPropertyArtist,
59 title, MPMediaItemPropertyTitle,
60 album, MPMediaItemPropertyAlbumTitle,
61 [currentMPItem valueForProperty:MPMediaItemPropertyArtwork], MPMediaItemPropertyArtwork,
62 nil];
63             [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo =mediaInfo;
64 }
65 }
66     else
67 {
68         self.infoLabel.text = @"...";
69         [self.playButton setTitle:@"Play"forState:UIControlStateNormal];
70         self.artworkImageView.image =nil;
71 }
72 }
73 
74 
75 - (void)viewDidAppear:(BOOL)animated
76 {
77 [super viewDidAppear:animated];
78     //注册远程控制事件
79 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
80 [self becomeFirstResponder];
81 }
82 
83 - (void)viewWillDisappear:(BOOL)animated
84 {
85 [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
86 [self resignFirstResponder];
87 [super viewWillDisappear:animated];
88 }
89 //接收和响应远程控制事件
90 - (void)remoteControlReceivedWithEvent: (UIEvent *) receivedEvent
91 {
92     if (receivedEvent.type ==UIEventTypeRemoteControl)
93 {
94         switch(receivedEvent.subtype)
95 {
96             //调用各自的动作方法实现事件的定向
97             caseUIEventSubtypeRemoteControlTogglePlayPause:
98 [self togglePlay:self];
99                 break;
100                 
101             caseUIEventSubtypeRemoteControlPreviousTrack:
102 [self goToPrevTrack:self];
103                 break;
104                 
105             caseUIEventSubtypeRemoteControlNextTrack:
106 [self goToNextTrack:self];
107                 break;
108                 
109             default:
110                 break;
111 }
112 }
113 }
114 
115 
116 //使用户能够远程控制媒体播放器,通过耳机或者活动栏。
117 -(BOOL)canBecomeFirstResponder
118 {
119     returnYES;
120 }
121 
122 - (void)playerItemDidReachEnd:(NSNotification *)notification
123 {
124 [self goToNextTrack:self];
125 }
126 
127 -(AVPlayerItem *)avItemFromMPItem:(MPMediaItem *)mpItem
128 {
129     NSURL *url =[mpItem valueForProperty:MPMediaItemPropertyAssetURL];
130 
131     AVPlayerItem *item =[AVPlayerItem playerItemWithURL:url];
132 
133 [[NSNotificationCenter defaultCenter]
134 addObserver:self
135 selector:@selector(playerItemDidReachEnd:)
136 name:AVPlayerItemDidPlayToEndTimeNotification
137      object:item];
138 
139     returnitem;
140 }
141 
142 -(void)startPlayback
143 {
144 [self.player play];
145     [self.playButton setTitle:@"Pause"forState:UIControlStateNormal];
146 [self updateNowPlaying];
147 }
148 
149 -(void)startPlaybackWithItem:(MPMediaItem *)mpItem
150 {
151 [self.player replaceCurrentItemWithPlayerItem:[self avItemFromMPItem:mpItem]];
152 [self.player seekToTime:kCMTimeZero];
153 [self startPlayback];
154 }
155 
156 -(void)pausePlayback
157 {
158 [self.player pause];
159     [self.playButton setTitle:@"Play"forState:UIControlStateNormal];
160 }
161 
162 - (IBAction)togglePlay:(id)sender
163 {
164     if (self.playlist.count > 0)
165 {
166         if (self.player.currentItem ==nil)
167 {
168             [self startPlaybackWithItem:[self.playlist objectAtIndex:0]];
169 }
170         else
171 {
172             //Player has an item, pause or resume playing it
173             BOOL isPlaying = self.player.currentItem && self.player.rate != 0;
174             if(isPlaying)
175 {
176 [self pausePlayback];
177 }
178             else
179 {
180 [self startPlayback];
181 }
182 }
183 }
184 }
185 
186 - (IBAction)queueFromLibrary:(id)sender
187 {
188     MPMediaPickerController *picker =[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
189     picker.delegate =self;
190     picker.allowsPickingMultipleItems =YES;
191     picker.prompt = @"Choose Some Music!";
192 [self presentViewController:picker animated:YES completion:NULL];
193 }
194 
195 - (IBAction)clearPlaylist:(id)sender
196 {
197 [self.player replaceCurrentItemWithPlayerItem:nil];
198 [self.playlist removeAllObjects];
199 [self updateNowPlaying];
200     [self.playButton setTitle:@"Play"forState:UIControlStateNormal];
201 }
202 
203 -(void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
204 {
205 [self dismissViewControllerAnimated:YES completion:NULL];
206 }
207 
208 -(void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
209 {
210     BOOL shallStartPlayer = self.playlist.count == 0;
211     
212 [self.playlist addObjectsFromArray:mediaItemCollection.items];
213     
214     if(shallStartPlayer)
215         [self startPlaybackWithItem:[self.playlist objectAtIndex:0]];
216 
217 [self dismissViewControllerAnimated:YES completion:NULL];
218 }
219 
220 - (IBAction)goToPrevTrack:(id)sender
221 {
222     if (self.playlist.count == 0)
223         return;
224     
225     if (CMTimeCompare(self.player.currentTime, CMTimeMake(5.0, 1)) > 0)
226 {
227 [self.player seekToTime:kCMTimeZero];
228 }
229     else
230 {
231         if (self.currentIndex == 0)
232 {
233             self.currentIndex = self.playlist.count - 1;
234 }
235         else
236 {
237             self.currentIndex -= 1;
238 }
239         MPMediaItem *previousItem =[self.playlist objectAtIndex:self.currentIndex];
240 [self startPlaybackWithItem:previousItem];
241 }
242 }
243 
244 - (IBAction)goToNextTrack:(id)sender
245 {
246     if (self.playlist.count == 0)
247         return;
248     
249     if (self.currentIndex == self.playlist.count - 1)
250 {
251         self.currentIndex = 0;
252 }
253     else
254 {
255         self.currentIndex += 1;
256 }
257     MPMediaItem *nextItem =[self.playlist objectAtIndex:self.currentIndex];
258 [self startPlaybackWithItem: nextItem];
259 }
260 
261 
262 @end

播放后台音频第2张

免责声明:文章转载自《播放后台音频》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android关于API level、buildToolVersion、CompileSdkVersion【jQuery日期处理】两个时间大小的比较下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

TortoiseGit安装、配置(Git 小乌龟安装)

然后关闭5ToroiseGit。以克隆验证中心项目为例,验证TortoiseGit配置是否正确。注意:在克隆代码之前,请确保您具有相关的项目代码权限。如果您没有权限,请具有主权限的同事帮助您分配登录gitlab的权限,在本地目标下载目录中获取SSH链接地址,右键单击--˃TortoiseGit--˃克隆,然后将SSH链接地址粘贴到URL,单击“确定”确认项目...

微信小游戏流量主广告接入指南!

游戏通过审核发布上线,累计注册用户达到1000后,可以在管理后台开启流量主功能。广告接入广告类型有三种:激励式视频、插屏和BannerBanner广告接入需要注意:1.广告要显示全,不能放在屏幕外。我的游戏被以上原因拒绝了两次。我的banner广告是放在底部正中间,取最小宽度200。也就是尽量的小,不影响游戏操作。激励视频按钮一定要有视频广告相关的提示!...

Python之路

Python之路引子与其感慨路难行,不如马上出发PythonPython之路(一):初识Python之路(二):基本数据类型(上)Python之路(三):基本数据类型(下)Python之路(四):函数介绍及使用Python之路(五):内置函数Python之路(六):迭代器,装饰器,生成器Python之路(七):字符串处理Python之路(八):基础模块(一)...

C# winform开发嵌套Chrome内核浏览器(WebKit.net)开发(一)

//Www.cnblogs.com/Maxq/p/6566558.htmlWebKit.net是WebKit的一个net包。使用它,。net程序可以非常方便地集成和使用webkit作为加载网页的容器。EventArgse){WebKit.WebKitBrowser=newWebKitBrowser();this.Controls.Add(浏览器);...

zabbix监控华为交换机

xmlversion=“1.0”encoding=“UTF-8”?...

可爱猫+python——定制化微信机器人

框架是模拟真实用户操作,只要不违法乱纪,是不用担心账号冻结问题的。...