如何在后台(IOS)播放音频文件时显示缩略图?

时间:2016-12-05 06:32:05

标签: ios objective-c audio

我正在使用MPMediaPickerController从媒体库中选择音频文件.code是:

    for (MPMediaItem *item in mediaItemCollection.items) {
            NSLog(@"%@",mediaItemCollection.items);
            NSURL* assetURL2 = [item valueForProperty:MPMediaItemPropertyAssetURL];}
    NSString* ext = [TSLibraryImport extensionForAssetURL:assetURL];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSURL* outURL = [[NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",thumbName]]] URLByAppendingPathExtension:ext];

现在我在服务器上传音频文件[outURL path],我获得了带url的音频文件。这个音频网址播放使用AVQueuePlayer(因为我必须逐个播放多个音频)。

对于背景音频播放,我必须在AppDelegate.m中编写代码,即:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

一切运行良好,但问题是音频缩略图在背景音乐播放中不显示。仅显示播放控件,持续时间和音乐文件名,默认显示音乐缩略图,但我想根据音频文件显示缩略图。

1 个答案:

答案 0 :(得分:0)

您可以为锁定屏幕图稿和已用时间添加此代码。

NSMutableDictionary albumInfo = [[NSMutableDictionary alloc] init];
[albumInfo setObject:_item.title forKey:MPMediaItemPropertyTitle];
[albumInfo setObject:_item.username forKey:MPMediaItemPropertyArtist];
int dur=CMTimeGetSeconds( player.currentItem.asset.duration) ;  //total duratiom
int now=CMTimeGetSeconds( [player currentTime]); // time elapsed
MPMediaItemArtwork *albumArt= [[MPMediaItemArtwork alloc] initWithImage: ART_IMAGE];// ART_IMAGE replace with your image name .

[albumInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
 [albumInfo setObject:[NSString stringWithFormat:@"%d",dur] forKey:MPMediaItemPropertyPlaybackDuration];
 [albumInfo setObject:[NSString stringWithFormat:@"%d",now]forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:albumInfo];