iOS 开发之-后台播放音乐

iOS4之后就支持后台播放音频了。只需下面两步就可以实现后台播放音频操作了:

1. 在Info.plist中,添加"Required background modes"键,其值设置如下图所示:

插入的 item

2. 添加AVFoundation框架,然后再添加如下两段代码

添加后台播放代码:

//后台播放音频设置  
    AVAudioSession *session = [AVAudioSession sharedInstance];    
    [session setActive:YES error:nil];    
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

以及设置app支持接受远程控制事件代码:

//让app支持接受远程控制事件  
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  

设置app支持接受远程控制事件,其实就是在dock中可以显示应用程序图标,同时点击该图片时,打开app

添加歌曲

//播放背景音乐  
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"background" ofType:@"mp3"];  
NSURL *url = [[NSURL alloc] initFileURLWithPath:musicPath];  
  
// 创建播放器  
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];  
[url release];  
[player prepareToPlay];  
[player setVolume:1];  
player.numberOfLoops = -1; //设置音乐播放次数  -1为一直循环  
[player play]; //播放  

这里我要在说一点可以实现手机拔出耳机时,让app暂停播放音乐,仅需在通知中心注册一个通知监听 AVAudioSessionRouteChangeNotification,代码如下:

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];

如果音频会话通道改变的话执行 routeChange:(自定义方法) 方法:

-(void)routeChange:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo;
    int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];
    //等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
    if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];
        //原设备为耳机则暂停
        /* Known values of route: 
         * "Headset" 
         * "Headphone" 
         * "Speaker" 
         * "SpeakerAndMicrophone" 
         * "HeadphonesAndMicrophone" 
         * "HeadsetInOut" 
         * "ReceiverAndMicrophone" 
         * "Lineout" 
         */ 
        if ([portDescription.portType isEqualToString:@"Headphones"]) {
            [self pause];
        }
    }
}

AVAudioSessionRouteChangeNotification 中 userinfo如下:

"NSLog(@"%@,,,,,,,,%@",AVAudioSessionRouteDescription,AVAudioSessionPortDescription);
//输出
"
); 
outputs = (
    ""
)>,,,,,,,,

    AVAudioSessionRouteChangeReasonKey = 2;

AVAudioPlayer 只能播放程序内缓存的音乐,如果想要播放 iTunes 里购买的音乐或导入的音乐,则需要用MediaPlayer.frameowork中有一个MPMusicPlayerController用于播放音乐库中的音乐。
MPMusicPlayerController加载音乐不同于前面的AVAudioPlayer是通过一个文件路径来加载,而是需要一个播放队列。在MPMusicPlayerController中提供了两个方法来加载播放队列:

  • (void)setQueueWithQuery:(MPMediaQuery *)query
  • (void)setQueueWithItemCollection:(MPMediaItemCollection *)itemCollection
    正是由于它的播放音频来源是一个队列,因此MPMusicPlayerController支持上一曲、下一曲等操作。

你可能感兴趣的:(iOS 开发之-后台播放音乐)