音效又稱短音頻,是一個聲音檔案,在 App 中擔綱點綴的角色,用於提升整體使用者體驗。幾乎所有手機 App 都少不了音效:按鈕點擊、任務完成、錯誤提示、遊戲反饋……它實作起來不難,但對使用者感受的影響卻不小。
先匯入 AudioToolbox.framework。
每次播放都重新載入音效檔案,是效能上的浪費。因此把音效的載入集中到一個單例中,在 App 啟動時一次載完,後續只查表播放。
Singleton.h:
#import <Foundation/Foundation.h> #import "Singleton.h" @interface SoundTools : NSObject singleton_interface(SoundTools) - (void)playSoundWithName:(NSString *)name; @end
接著把 App 要用到的所有音效放進一個名為 sound.bundle 的資料夾中,加入專案 Bundle。
Singleton.m 的初始化部分:
#import "SoundTools.h"
#import <AudioToolbox/AudioToolbox.h>
@interface SoundTools () {
NSDictionary *_soundDict; // 音訊字典
}
@end
@implementation SoundTools
singleton_implementation(SoundTools)
- (id)init {
self = [super init];
if (self) {
_soundDict = [self loadSounds]; // 完成所有音訊檔案的載入
}
return self;
}
系統聲音服務透過 SystemSoundID 播放聲音檔案。同一個聲音檔可以建立多個 SystemSoundID。這是一套 C 語言框架,為避免檔案被重複載入,通常搭配單例模式使用。
#pragma mark 載入指定的音訊檔案
- (SystemSoundID)loadSoundWithURL:(NSURL *)url {
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
return soundID;
}
思路是:既然要知道載入哪些檔案,那就把音效集中放進一個 bundle,執行時直接遍歷該目錄即可。
#pragma mark 載入所有的音訊檔案
- (NSDictionary *)loadSounds {
// 1. 取出 bundle 的路徑
NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePath = [mainBundlePath stringByAppendingPathComponent:@"sound.bundle"];
// 2. 遍歷目錄
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundlePath error:nil];
// 3. 為每個檔案建立 SoundID 並記錄
NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithCapacity:array.count];
[array enumerateObjectsUsingBlock:^(NSString *fileName, NSUInteger idx, BOOL *stop) {
NSString *filePath = [bundlePath stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
SystemSoundID soundID = [self loadSoundWithURL:fileURL];
[dictM setObject:@(soundID) forKey:fileName]; // 以檔名為鍵
}];
return dictM;
}
#pragma mark - 播放音訊
- (void)playSoundWithName:(NSString *)name {
SystemSoundID soundID = [_soundDict[name] unsignedLongValue];
NSLog(@"%ld", (long)soundID);
// 斷言:防止音效名被誤改而找不到檔案
NSAssert(soundID > 0, @"%@ 聲音檔案不存在!", name);
AudioServicesPlaySystemSound(soundID);
}
在控制器中呼叫即可:
- (void)clickMe {
[[SoundTools sharedSoundTools] playSoundWithName:@"game_overs.mp3"];
}
NSURL *url = [[NSBundle mainBundle] URLForResource:@"bullet.mp3" withExtension:nil]; SystemSoundID soundID = 0; // 建立聲音並取得 soundID AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID); // 播放聲音 AudioServicesPlaySystemSound(soundID);
這種寫法每按一次就重新載入一次檔案,在快速連續觸發(例如連續點擊射擊)時會造成明顯的延遲。
AudioServicesPlayAlertSound 與 AudioServicesPlaySystemSound 的差異:前者在裝置靜音時會改為震動以提示使用者,後者則完全遵守靜音原則只播放聲音。選擇哪一個要看你的提示語意——「警告」適合前者,「氛圍音效」適合後者。AudioServicesDisposeSystemSoundID 釋放,否則在單例生命週期很長的 App 中會累積系統資源。