最近在做蓝牙连接外设的APP,用到音频播放与录音等功能,这类APP第一次做,查资料话了不少时间,方便以后查阅。

1、我用的时AVAudioPlayer需要导入AVFoundation.framework系统控件

2、设置plist属性,在工程里找到plist文件右键选择Add Row,输入UIBackgroundModes,添加一个属性audio

 

3、Appdelegate.m中,设置接收远程事件(用耳机、锁屏操作等),此操作也可以放在viewcontroller的viewWillAppear与viewWillDisapear中

- (void)applicationWillResignActive:(UIApplication *)application

{

    [application beginReceivingRemoteControlEvents];

    [application becomeFirstResponder];

}

//App在前台时取消接收

- (void)applicationWillEnterForeground:(UIApplication *)application

{

    [application endReceivingRemoteControlEvents];

    [application resignFirstResponder];

    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

//可以成为第一相应者

- (BOOL)canBecomeFirstResponder {

    return YES;

}

4、设置AVAudioSession属性,让应用支持后台(可以写在播放页面)

    AVAudioSession *session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    [session setActive:YES error:nil];

5、初始化AVAudioPlayer播放器(在UIViewcontroller中)

  if (_player == nil) {

            NSError *error = nil;

            _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:&error];

            _player.numberOfLoops = -1;

            if (error) {

                NSLog(@"player music %@", [error localizedDescription]);

            }

            _player.delegate = self;

        }

    [self configNowPlayingInfoCenter];//设置锁屏时MP3信息

        [_player prepareToPlay];

        [_player play];

6、重写UIResponder的方法,这样可以监控到播放、暂停、停止、上、下一曲事件,一般在切换曲目时候调用[self configNowPlayingInfoCenter];

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {

    if (event.type == UIEventTypeRemoteControl) {

        [self configNowPlayingInfoCenter];

        NSLog(@"UIEventTypeRemoteControl");

        switch (event.subtype) {

            case UIEventSubtypeRemoteControlPlay:

            {}break;

            case UIEventSubtypeRemoteControlPause:

            {} break;

            case UIEventSubtypeRemoteControlStop:

            {}break;

            case UIEventSubtypeRemoteControlNextTrack:

            {}break;

            case UIEventSubtypeRemoteControlPreviousTrack:

    {}break;                

            default:

                break;

        }

    }

    else if (event.type == UIEventTypeMotion) {

        NSLog(@"UIEventTypeMotion");

    }

    else if (event.type == UIEventTypeTouches) {

        NSLog(@"UIEventTypeTouches");

    }

}

7、实现configNowPlayingInfoCenter方法,iOS5以下需寻找其他方法,

-(void)configNowPlayingInfoCenter{

    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {

        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"1.mp3"];

        UIImage *mp3Image = [self getMP3Pic:[NSURL fileURLWithPath:path]];

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

        [info setObject:@"sexy R&B" forKey:MPMediaItemPropertyTitle];//song name

        [info setObject:@"foreigner" forKey:MPMediaItemPropertyArtist];//singer

        [info setObject:@"foreign zone" forKey:MPMediaItemPropertyAlbumTitle];//album

        [info setObject:[NSNumber numberWithDouble:self.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];

        if (mp3Image) {

            MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:mp3Image];

            [info setObject:artWork forKey:MPMediaItemPropertyArtwork];

        }

        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:info];

    }

}

//获取本地MP3的图片

-(UIImage *)getMP3Pic:(NSURL *)url

{

    AVAsset *asset = [AVAsset assetWithURL:url];

    for (AVMetadataItem *metadataItem in asset.commonMetadata) {

        if ([metadataItem.commonKey isEqualToString:@"artwork"]){

            return [UIImage imageWithData:(NSData *)metadataItem.value];

        }

    }

    return nil;

}

OK,一切都顺利的话,播放MP3,退到后台锁屏后点亮屏效果如下

另外如果要显示歌词,那么就要用MP3的图和label合成后再设置到setNowPlayingInfo