這是一個把播放核心功能都做過一遍的播放器範例:上一曲/下一曲、暫停與續播、歌詞隨播放進度滾動並放大當前句、拖動進度條時歌曲與歌詞同步跳轉。另外還做了兩件平時容易被忽略的事——用 Time Profiler 做效能分析,以及替核心類別補上 XCTest 單元測試。所有功能都已在真機上驗證,包含背景播放與鎖屏資訊顯示。
先把播放能力封裝成單例,對外只暴露「播放/暫停/停止音樂」與「播放/釋放音效」四個動作。這裡有兩個設計決定值得說明:用字典快取 AVAudioPlayer,讓同一首歌暫停後再播能直接從記憶體續上;在 +initialize 中設定 Audio Session 類別。
#import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> @interface ZYAudioManager : NSObject + (instancetype)defaultManager; // 播放音樂 - (AVAudioPlayer *)playingMusic:(NSString *)filename; - (void)pauseMusic:(NSString *)filename; - (void)stopMusic:(NSString *)filename; // 播放音效 - (void)playSound:(NSString *)filename; - (void)disposeSound:(NSString *)filename; @end
#import "ZYAudioManager.h"
@interface ZYAudioManager ()
@property (nonatomic, strong) NSMutableDictionary *musicPlayers;
@property (nonatomic, strong) NSMutableDictionary *soundIDs;
@end
static ZYAudioManager *_instance = nil;
@implementation ZYAudioManager
+ (void)initialize {
// 設定音訊工作階段
AVAudioSession *session = [AVAudioSession sharedInstance];
// 播放類型:會自動中斷其他 App 的播放
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
// 啟用工作階段
[session setActive:YES error:nil];
}
+ (instancetype)defaultManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
// 三重保險,確保 alloc / init / copy 都拿到同一個物件
- (instancetype)init {
__block ZYAudioManager *temp = self;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if ((temp = [super init]) != nil) {
_musicPlayers = [NSMutableDictionary dictionary];
_soundIDs = [NSMutableDictionary dictionary];
}
});
self = temp;
return self;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
// 播放音樂
- (AVAudioPlayer *)playingMusic:(NSString *)filename {
if (filename == nil || filename.length == 0) return nil;
AVAudioPlayer *player = self.musicPlayers[filename];
// 先查快取
if (!player) {
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
if (!url) return nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if (![player prepareToPlay]) return nil;
self.musicPlayers[filename] = player; // 新建的才快取
}
if (![player isPlaying]) {
[player play]; // 已在播放就不重複呼叫
}
return player;
}
- (void)pauseMusic:(NSString *)filename {
if (filename == nil || filename.length == 0) return;
AVAudioPlayer *player = self.musicPlayers[filename];
if ([player isPlaying]) {
[player pause];
}
}
- (void)stopMusic:(NSString *)filename {
if (filename == nil || filename.length == 0) return;
AVAudioPlayer *player = self.musicPlayers[filename];
[player stop];
[self.musicPlayers removeObjectForKey:filename]; // 必須移除!
}
// 播放音效
- (void)playSound:(NSString *)filename {
if (!filename) return;
SystemSoundID soundID = (int)[self.soundIDs[filename] unsignedLongValue];
if (!soundID) {
NSURL *url = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
if (!url) return;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
self.soundIDs[filename] = @(soundID);
}
AudioServicesPlaySystemSound(soundID);
}
// 銷毀音效
- (void)disposeSound:(NSString *)filename {
if (!filename) return;
SystemSoundID soundID = (int)[self.soundIDs[filename] unsignedLongValue];
if (soundID) {
AudioServicesDisposeSystemSoundID(soundID);
[self.soundIDs removeObjectForKey:filename];
}
}
@end
這裡藏著一個我實際踩到的 bug:stopMusic: 中如果忘記從字典移除已停止的 player,那麼下次播放同一首歌時,會從上次停止的進度續播,而不是從頭開始。因為切歌(上一曲/下一曲)走的正是 stop 流程,導致每首歌永遠從上次的位置開始。邏輯上也很直觀——stop 代表「這次播放結束」,快取自然該失效;pause 才是「保留進度待續播」。
另一個真機才會顯現的問題:想在背景播放音樂,除了 AppDelegate 與 plist 的 background modes 設定之外,還必須把 session 類別設為 AVAudioSessionCategoryPlayback。模擬器上沒設也能背景播放,真機卻會靜音,這點在 Stack Overflow 上找到確認。
這個單例被整個 App 依賴,必須確保它沒有錯,因此我為它寫了 XCTest。特別是「單例性」測試,一定要在並發條件下驗證。
#import <XCTest/XCTest.h>
#import "ZYAudioManager.h"
#import <AVFoundation/AVFoundation.h>
@interface ZYAudioManagerTests : XCTestCase
@property (nonatomic, strong) AVAudioPlayer *player;
@end
static NSString *_fileName = @"10405520.mp3";
@implementation ZYAudioManagerTests
/** 測試是否為單例(必須在並發條件下測) */
- (void)testAudioManagerSingle {
NSMutableArray *managers = [NSMutableArray array];
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 5; i++) {
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
ZYAudioManager *tempManager = [[ZYAudioManager alloc] init];
[managers addObject:tempManager];
});
}
ZYAudioManager *managerOne = [ZYAudioManager defaultManager];
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[managers enumerateObjectsUsingBlock:^(ZYAudioManager *obj,
NSUInteger idx,
BOOL * _Nonnull stop) {
XCTAssertEqual(managerOne, obj, @"ZYAudioManager is not single");
}];
});
}
/** 測試是否正常播放 */
- (void)testPlayingMusic {
self.player = [[ZYAudioManager defaultManager] playingMusic:_fileName];
XCTAssertTrue(self.player.playing, @"ZYAudioManager is not PlayingMusic");
}
/** 測試是否正常停止 */
- (void)testStopMusic {
if (self.player == nil) {
self.player = [[ZYAudioManager defaultManager] playingMusic:_fileName];
}
if (self.player.playing == NO) [self.player play];
[[ZYAudioManager defaultManager] stopMusic:_fileName];
XCTAssertFalse(self.player.playing, @"ZYAudioManager is not StopMusic");
}
/** 測試是否正常暫停 */
- (void)testPauseMusic {
if (self.player == nil) {
self.player = [[ZYAudioManager defaultManager] playingMusic:_fileName];
}
if (self.player.playing == NO) [self.player play];
[[ZYAudioManager defaultManager] pauseMusic:_fileName];
XCTAssertFalse(self.player.playing, @"ZYAudioManager is not pauseMusic");
}
@end
為什麼要用 dispatch_group 而不是直接跑五個併發?因為必須等所有並發都結束才能比較結果。否則可能出現 x 執行緒已執行完、其對應的物件已有值,而 y 執行緒還沒初始化、物件仍是 nil,這種「測試時序造成的假失敗」最難排查。
#import "ZYMusicViewController.h"
#import "ZYPlayingViewController.h"
#import "ZYMusicTool.h"
#import "ZYMusic.h"
#import "ZYMusicCell.h"
@interface ZYMusicViewController ()
@property (nonatomic, strong) ZYPlayingViewController *playingVc;
@property (nonatomic, assign) int currentIndex;
@end
@implementation ZYMusicViewController
- (ZYPlayingViewController *)playingVc {
if (_playingVc == nil) {
_playingVc = [[ZYPlayingViewController alloc] initWithNibName:@"ZYPlayingViewController"
bundle:nil];
}
return _playingVc;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"音樂播放器";
}
#pragma mark ----TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ZYMusicTool musics].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ZYMusicCell *cell = [ZYMusicCell musicCellWithTableView:tableView];
cell.music = [ZYMusicTool musics][indexPath.row];
return cell;
}
#pragma mark ----TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[ZYMusicTool setPlayingMusic:[ZYMusicTool musics][indexPath.row]];
// 先把原本那首的播放狀態改回 NO
ZYMusic *preMusic = [ZYMusicTool musics][self.currentIndex];
preMusic.playing = NO;
ZYMusic *music = [ZYMusicTool musics][indexPath.row];
music.playing = YES;
// 只刷新受影響的兩列,避免整表 reload
NSArray *indexPaths = @[[NSIndexPath indexPathForItem:self.currentIndex inSection:0],
indexPath];
[self.tableView reloadRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationNone];
self.currentIndex = (int)indexPath.row;
[self.playingVc show];
}
@end

這個畫面的細節最多。進度條的推進用 NSTimer 驅動,並在所有不需要它的時機都做了 invalidate。
拖動時踩到一個坑:滑塊位置與歌曲進度對不上。問題出在手势的位移量處理——translationInView: 回傳的是「自上次觸發以來的累積位移」,若每次都不歸零,數值就會不斷疊加。
// 取得位移量 CGPoint point = [sender translationInView:sender.view]; // 用完立刻歸零,避免重複疊加 [sender setTranslation:CGPointZero inView:sender.view];
歌詞用 ZYLrcView 呈現。要注意它繼承自 UIImageView,而 UIImageView 預設 userInteractionEnabled 為 NO,必須手動打開才能捲動。
#import <UIKit/UIKit.h> @interface ZYLrcView : UIImageView @property (nonatomic, assign) NSTimeInterval currentTime; @property (nonatomic, copy) NSString *fileName; @end
#import "ZYLrcView.h"
#import "ZYLrcLine.h"
#import "ZYLrcCell.h"
#import "UIView+AutoLayout.h"
@interface ZYLrcView () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *lrcLines;
@property (nonatomic, assign) int currentIndex; // 當前歌詞在陣列中的索引
@end
@implementation ZYLrcView
- (NSMutableArray *)lrcLines {
if (_lrcLines == nil) {
_lrcLines = [ZYLrcLine lrcLinesWithFileName:self.fileName];
}
return _lrcLines;
}
// 切歌時清掉舊歌詞
- (void)setFileName:(NSString *)fileName {
if ([_fileName isEqualToString:fileName]) return;
_fileName = [fileName copy];
[_lrcLines removeAllObjects];
_lrcLines = nil;
[self.tableView reloadData];
}
- (void)setCurrentTime:(NSTimeInterval)currentTime {
if (_currentTime > currentTime) {
self.currentIndex = 0; // 往回拖,重置游標
}
_currentTime = currentTime;
int minute = currentTime / 60;
int second = (int)currentTime % 60;
int msecond = (currentTime - (int)currentTime) * 100;
NSString *currentTimeStr = [NSString stringWithFormat:@"%02d:%02d.%02d",
minute, second, msecond];
// 從上一句的索引開始找,而不是每次從頭掃
for (int i = self.currentIndex; i < self.lrcLines.count; i++) {
ZYLrcLine *currentLine = self.lrcLines[i];
NSString *currentLineTime = currentLine.time;
NSString *nextLineTime = nil;
if (i + 1 < self.lrcLines.count) {
nextLineTime = self.lrcLines[i + 1].time;
}
// 落在「本 (>=) 與下一句 (<)」之間,就是當前句
if (([currentTimeStr compare:currentLineTime] != NSOrderedAscending) &&
([currentTimeStr compare:nextLineTime] == NSOrderedAscending) &&
(self.currentIndex != i)) {
NSArray *reloadLines = @[[NSIndexPath indexPathForItem:self.currentIndex inSection:0],
[NSIndexPath indexPathForItem:i inSection:0]];
self.currentIndex = i;
[self.tableView reloadRowsAtIndexPaths:reloadLines
withRowAnimation:UITableViewRowAnimationNone];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.currentIndex
inSection:0]
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
}
}
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self commitInit];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self commitInit];
}
return self;
}
- (void)commitInit {
self.userInteractionEnabled = YES; // UIImageView 預設 NO,必須打開
self.image = [UIImage imageNamed:@"28131977_1383101943208"];
self.contentMode = UIViewContentModeScaleToFill;
self.clipsToBounds = YES;
UITableView *tableView = [[UITableView alloc] init];
tableView.delegate = self;
tableView.dataSource = self;
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
tableView.backgroundColor = [UIColor clearColor];
self.tableView = tableView;
[self addSubview:tableView];
[self.tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.lrcLines.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ZYLrcCell *cell = [ZYLrcCell lrcCellWithTableView:tableView];
cell.lrcLine = self.lrcLines[indexPath.row];
// 當前句放大加粗
if (indexPath.row == self.currentIndex) {
cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
} else {
cell.textLabel.font = [UIFont systemFontOfSize:13];
}
return cell;
}
- (void)layoutSubviews {
[super layoutSubviews];
// 上下各留半屏,讓當前句能捲到畫面中央
self.tableView.contentInset = UIEdgeInsetsMake(self.frame.size.height / 2, 0,
self.frame.size.height / 2, 0);
}
@end
歌詞同步的整體思路是:先把 LRC 解析成「時間 → 句子」的列表,播放過程中持續把當前時間傳進來,判斷它落在哪兩句之間,就切到那一句。
這裡做了一個關鍵優化。CADisplayLink 每毫秒觸發一次,一秒就是上千次回呼,一首歌四五分鐘下來高達數十萬次,若每次都從頭遍歷歌詞陣列,效能會非常難看。因此記錄了上一句的索引 currentIndex,正常播放時只需從該索引往後找一兩句即可命中,運算量大幅下降。這也是我用 Time Profiler 分析後調整的地方之一。

鎖屏要顯示歌名、歌手與專輯封面,做法是設定 MPNowPlayingInfoCenter.defaultCenter.nowPlayingInfo 字典;而要在鎖屏或耳機線控上接收播放/暫停/切歌指令,則需實作 MPRemoteCommandCenter 的相關 command。兩者加上前面提到的 background modes 與 AVAudioSessionCategoryPlayback,才是完整的背景播放方案。
回顧整個專案,值得帶走的三點經驗是:快取字典要明確定義「何時失效」(stop 與 pause 語意不同);真機與模擬器的行為差異(背景播放)務必提早驗證;以及效能問題要靠工具量化——毫秒級回呼搭配索引游標,比任何直覺上的微調都有效。