第一步:
第二步:
in the didFinishLaunchingWithOptions.
UIDevice *thisDevice = [UIDevice
currentDevice];
if([thisDevice
respondsToSelector:@selector(isMultitaskingSupported)]
&& thisDevice.multitaskingSupported)
{
UIBackgroundTaskIdentifier backgroundTask = [application
beginBackgroundTaskWithExpirationHandler:^{
/* just fail if this happens. */
NSLog(@"BackgroundTask
Expiration Handler is called");
[application
endBackgroundTask:backgroundTask];
}];
}
第三步:
在播放的时候添加以下代码:
AVAudioSession *session = [AVAudioSession
sharedInstance];
[session setActive:YES error:nil];
[session setActive:YES error:nil];
[session
setCategory:AVAudioSessionCategoryPlayback
error:nil];
只需要三步就能在后台播放网络音频文件。
如果需要设置锁屏播放信息,添加代码:
NSMutableDictionary *dict = [[NSMutableDictionary
alloc]
init];
dict[MPMediaItemPropertyTitle] = self.audioTrackEntity.title;//歌曲名设置
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:
case UIEventSubtypeRemoteControlPause:
NSLog(@"RemoteControlEvents: pause");
break;
case
UIEventSubtypeRemoteControlPlay:
NSLog(@"RemoteControlEvents:
play");
break;
case
UIEventSubtypeRemoteControlNextTrack:
NSLog(@"RemoteControlEvents: playNext");
break;
case
UIEventSubtypeRemoteControlPreviousTrack:
NSLog(@"RemoteControlEvents:
playPrev");
break;
}
}
break;
}
}
}