本文實作一個音樂播放器,重點在於「後台播放」與「鎖屏界面顯示歌曲資訊」兩大功能,並搭配唱片旋轉動畫與自動續播下一首。
最終效果圖:

後台播放需要三個步驟,第一步是在應用進入後台時,讓應用保持運行:
- (void)applicationDidEnterBackground:(UIApplication *)application {
// 後台播放步驟之一:讓應用在後台運行
[application beginBackgroundTaskWithExpirationHandler:nil];
}
工具類用字典快取所有播放器,一首都對應一個 AVAudioPlayer。後台播放的第三步——設定音頻會話類型——也在此完成:
#import <AVFoundation/AVFoundation.h>
@implementation SongTool
static NSMutableDictionary *_audioPlayerDict;
+ (void)initialize {
_audioPlayerDict = [NSMutableDictionary dictionary];
// 後台播放三步曲之第三步:設置音頻會話類型
[self setupForBackgroundPlay];
}
+ (void)setupForBackgroundPlay {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[session setActive:YES error:nil];
}
// 播放音樂,返回播放器以便設置代理
+ (AVAudioPlayer *)playMusic:(NSString *)filename {
if (!filename) return nil;
AVAudioPlayer *audioPlayer = _audioPlayerDict[filename];
if (!audioPlayer) {
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
if (!url) return nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer prepareToPlay];
_audioPlayerDict[filename] = audioPlayer;
}
if (!audioPlayer.isPlaying) {
[audioPlayer play];
}
return audioPlayer;
}
// 停止音樂並從字典移除
+ (void)stopMusic:(NSString *)filename {
if (!filename) return;
AVAudioPlayer *audioPlayer = _audioPlayerDict[filename];
if (audioPlayer.isPlaying) {
[audioPlayer stop];
[_audioPlayerDict removeObjectForKey:filename];
}
}
@end
模型 Song 描述一首歌曲的屬性(歌名、文件名、歌手、圖片等),並用 playing 標記是否正在播放,供 Cell 決定是否旋轉唱片。
@interface Song : NSObject @property (copy, nonatomic) NSString *name; // 歌名 @property (copy, nonatomic) NSString *filename; // 文件名 @property (copy, nonatomic) NSString *singer; // 藝術家 @property (copy, nonatomic) NSString *singerIcon;// 頭像 @property (copy, nonatomic) NSString *icon; // 鎖屏大圖 @property (nonatomic, assign, getter = isPlaying) BOOL playing; @end
自訂 Cell 攔截 setMusic:,根據 isPlaying 決定是否啟動唱片旋轉動畫:
- (void)setMusic:(Song *)music {
_music = music;
self.textLabel.text = music.name;
self.detailTextLabel.text = music.singer;
self.imageView.image = [UIImage circleImageWithName:music.singerIcon borderWidth:2 borderColor:[UIColor skyBlueColor]];
if (music.isPlaying) {
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
} else {
[self.link invalidate];
self.link = nil;
self.imageView.transform = CGAffineTransformIdentity;
}
}
// 角速度:45°/s,即 8 秒一圈
- (void)update {
CGFloat angle = self.link.duration * M_PI_4;
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, angle);
}
透過 MPNowPlayingInfoCenter 在鎖屏界面顯示歌曲資訊。即時更新 MPMediaItemPropertyArtwork 甚至能達到即時換歌詞的效果:
#import <MediaPlayer/MediaPlayer.h>
- (void)showInfoInLockedScreen:(Song *)music {
// 健壯性寫法:存在該類才能在鎖屏時顯示
if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[MPMediaItemPropertyTitle] = music.name;
info[MPMediaItemPropertyArtist] = music.singer;
info[MPMediaItemPropertyAlbumTitle] = music.singer;
info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:music.icon]];
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
}
}
由於 AVAudioPlayer 的代理沒有監聽進度的方法,需自行開啟 CADisplayLink 定時器。一曲播放完畢時,計算下一首的行號並自動續播:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
int nextRow = selectedPath.row + 1;
if (nextRow == self.songArr.count) {
nextRow = 0;
}
NSIndexPath *nextPath = [NSIndexPath indexPathForRow:nextRow inSection:selectedPath.section];
[self.tableView selectRowAtIndexPath:nextPath animated:YES scrollPosition:UITableViewScrollPositionTop];
[self tableView:self.tableView didSelectRowAtIndexPath:nextPath];
}
實現後台播放的關鍵三步驟為:
① 在 applicationDidEnterBackground 呼叫 beginBackgroundTaskWithExpirationHandler;
② 設定合適的音頻會話類型;
③ 正確配置 AVAudioSession 並激活。
而鎖屏歌詞則靠 MPNowPlayingInfoCenter 加上即時更新的 artwork 來呈現,唱片旋轉動畫則由 CADisplayLink 驅動 CGAffineTransformRotate 完成。