您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 播放系統音效與自訂音效的完整做法

編輯:iOS 開發綜合

要在 App 裡播放短音效,AudioToolbox 提供的 AudioServicesPlaySystemSound 是最輕量的一條路。以下整理可用資源、封裝方式,以及一個容易踩到的崩潰陷阱。

先找對素材

網路上有一份整理得相當完整的 iOS 系統音效清單,列出了各音效的 ID 與存放位置,即使系統版本更新,這份清單仍有參考價值:
https://github.com/TUNER88/iOSSystemSoundsLibrary

Stack Overflow 上也有實用的討論與做法:
https://stackoverflow.com/questions/7831671/playing-system-sound-without-importing-your-own

另外有一個把各 framework 標頭檔打包出來的專案,其中正好包含需要用到的 AudioToolbox:
https://github.com/EthanArbuckle/IOS-7-Headers

封裝成單例類別

若要在專案各處播放短音效,包一個單例最方便。不用單例當然也完全可以,只是呼叫端要多處理物件生命週期。

// CHAudioPlayer.h
// Created by HuangCharlie on 3/26/15.

#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "SynthesizeSingleton.h"

@interface CHAudioPlayer : NSObject {
}

DEF_SINGLETON_FOR_CLASS(CHAudioPlayer);

// 播放系統震動
- (void)updateWithVibration;

// 以 ID 播放系統音效,清單見:
// https://github.com/TUNER88/iOSSystemSoundsLibrary
- (void)updateWithSoundID:(SystemSoundID)soundId;

// 播放專案內的音效資源
- (void)updateWithResource:(NSString *)resourceName ofType:(NSString *)type;

// 實際播放
- (void)play;

@end
// CHAudioPlayer.m
// Created by HuangCharlie on 3/26/15.

#import "CHAudioPlayer.h"

@interface CHAudioPlayer ()
@property (nonatomic, assign) SystemSoundID soundID;
@end

@implementation CHAudioPlayer

IMPL_SINGLETON_FOR_CLASS(CHAudioPlayer);

// 震動
- (void)updateWithVibration {
    self.soundID = kSystemSoundID_Vibrate;
}

- (void)updateWithSoundID:(SystemSoundID)soundId {
    self.soundID = soundId;
}

// 播放專案內的音效資源,例如 wav
- (void)updateWithResource:(NSString *)resourceName ofType:(NSString *)type {
    [self dispose];

    NSString *path = [[NSBundle mainBundle] pathForResource:resourceName ofType:type];
    if (path) {
        // 注冊聲音到系統
        NSURL *url = [NSURL fileURLWithPath:path];
        CFURLRef inFileURL = (__bridge CFURLRef)url;

        SystemSoundID tempSoundId;
        OSStatus error = AudioServicesCreateSystemSoundID(inFileURL, &tempSoundId);
        if (error == kAudioServicesNoError) {
            self.soundID = tempSoundId;
        }
    }
}

- (void)play {
    AudioServicesPlaySystemSound(self.soundID);
}

- (void)dispose {
    AudioServicesDisposeSystemSoundID(self.soundID);
}

@end

一個容易忽略的崩潰點

使用自訂資源時會走 updateWithResource:。其中這兩行如果合寫在一起,很可能因為其他因素造成 crash,建議分開寫:

// 注冊聲音到系統
NSURL *url = [NSURL fileURLWithPath:path];
CFURLRef inFileURL = (__bridge CFURLRef)url;

另外還有兩點值得注意:

  • AudioServicesCreateSystemSoundID 成功配置之後,對應的 AudioServicesDisposeSystemSoundID 就必須被呼叫,否則是資源洩漏。上面範例在每次重新設定前先 dispose,是為了避免舊的 soundID 遺留在系統裡。
  • System Sound 適合短促的提示音,若你要播放背景音樂或較長的音檔,應該改用 AVAudioPlayer 或 AVPlayer。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved