iOS 中若要播放短音效或觸發震動,可使用 AudioToolbox 的 System Sound API。它適合提示音、按鈕音與簡單回饋,不適合長時間播放音樂。
可建立 WQPlaySound 類別,封裝震動、系統音效與自訂音檔三種初始化方式。
- (id)initForPlayingVibrate {
self = [super init];
if (self) {
soundID = kSystemSoundID_Vibrate;
}
return self;
}
- (void)play {
AudioServicesPlaySystemSound(soundID);
}
若音檔放在 App bundle,可先取得 file URL,再用 AudioServicesCreateSystemSoundID 建立 SystemSoundID。
SystemSoundID theSoundID;
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"tap" withExtension:@"aif"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID);
AudioServicesPlaySystemSound(theSoundID);
使用完畢後,應呼叫 AudioServicesDisposeSystemSoundID 釋放資源。使用前記得把 AudioToolbox.framework 加入專案。
呼叫方式可分為震動、系統音效與自訂音檔三種,核心都是取得 SystemSoundID 後播放。