您的位置:首页 > 理论基础 > 计算机网络

iOS后台播放网络音乐

2015-07-30 22:09 633 查看
第一步:



第二步:

in the didFinishLaunchingWithOptions.

[b]
[b]UIDevice
*thisDevice = [UIDevice
currentDevice[/b]];[/b]
[b]
[b]if
([thisDevice
respondsToSelector:@selector[/b](isMultitaskingSupported)][/b]
[b] && thisDevice.[b]multitaskingSupported[/b])
{[/b]
[b]
[b]UIBackgroundTaskIdentifier
backgroundTask = [application
beginBackgroundTaskWithExpirationHandler[/b]:^{[/b]
[b]
[b]/* just fail if this happens. */
[/b][/b]
[b]
[b]NSLog
(@"BackgroundTask
Expiration Handler is called"
[/b]);[/b]
[b] [application
[b]endBackgroundTask
[/b]:backgroundTask];[/b]
}];
}

第三步:

在播放的时候添加以下代码:

AVAudioSession *session = [AVAudioSessionsharedInstance];

[session
setActive:YESerror:nil];
[session
setCategory[b]:AVAudioSessionCategoryPlaybackerror:nil];[/b]

只需要三步就能在后台播放网络音频文件。

如果需要设置锁屏播放信息,添加代码:

NSMutableDictionary *dict = [[NSMutableDictionary
alloc]
init];

dict[MPMediaItemPropertyTitle] =
self.audioTrackEntity.title;//歌曲名设置
dict[MPMediaItemPropertyArtist] =
@"";//歌手名设置
dict[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork
alloc] initWithImage:nil];//专辑图片设置
[[MPNowPlayingInfoCenter
defaultCenter]
setNowPlayingInfo:dict];

这个时候屏幕上会出现正在播放的音乐信息,如果需要监听“上一首”,“下一首”,“暂停”,“播放”
in the didFinishLaunchingWithOptions. 添加代码:
//告诉系统,我们要接受远程控制事件
[[UIApplication
sharedApplication]
beginReceivingRemoteControlEvents];

在AppDelegate.m 添加函数
//响应远程音乐播放控制消息
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
if (receivedEvent.type
== UIEventTypeRemoteControl) {
switch (receivedEvent.subtype)
{

case
UIEventSubtypeRemoteControlPause:

NSLog(@"RemoteControlEvents: pause");
break;
case
UIEventSubtypeRemoteControlPlay:
NSLog(@"RemoteControlEvents:
play");

break;
case
UIEventSubtypeRemoteControlNextTrack:

NSLog(@"RemoteControlEvents: playNext");
break;
case
UIEventSubtypeRemoteControlPreviousTrack:
NSLog(@"RemoteControlEvents:
playPrev");

break;

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: