iOS后台播放网络音乐

第一步:
     

第二步:

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 setCategory:AVAudioSessionCategoryPlayback error:nil];

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

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

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[
MPMediaItemPropertyTitle] = self.audioTrackEntity.title;//歌曲名设置
    dict[MPMediaItemPropertyArtist] = @"";//歌手名设置
    dict[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork allocinitWithImage: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;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值