iOS 播放系统铃声、震动、自定义铃声以及循环播放

前言

很多时候我们需要播放音频来提醒用户,调用系统铃声是不错的选择,例如自定义一个截图操作,可以调用系统的快门声;做一个VoIP通话服务,可以循环播放一段自定义铃声和震动,然后接通或者挂断时候手动停止,等等

下文所有的功能均使用系统框架AudioToolbox

  • 播放系统铃声

func AudioServicesPlaySystemSound(_ inSystemSoundID: SystemSoundID)

使用AudioServicesPlaySystemSound方法,参数是你要播放的SoundID,然后系统会播放这个铃声一次,不会循环播放,系统的soundid表见下表

Sound ID File name (iPhone) File name (iPod Touch) Category Note
1000 new-mail.caf new-mail.caf MailReceived
1001 mail-sent.caf mail-sent.caf MailSent
1002 Voicemail.caf Voicemail.caf VoicemailReceived
1003 ReceivedMessage.caf ReceivedMessage.caf SMSReceived
1004 SentMessage.caf SentMessage.caf SMSSent
1005 alarm.caf sq_alarm.caf CalendarAlert
1006 low_power.caf low_power.caf LowPower
1007 sms-received1.caf sms-received1.caf SMSReceived_Alert
1008 sms-received2.caf sms-received2.caf SMSReceived_Alert
1009 sms-received3.caf sms-received3.caf SMSReceived_Alert
1010 sms-received4.caf sms-received4.caf SMSReceived_Alert
1011 - - SMSReceived_Vibrate
1012 sms-received1.caf sms-received1.caf SMSReceived_Alert
1013 sms-received5.caf sms-received5.caf SMSReceived_Alert
1014 sms-received6.caf sms-received6.caf SMSReceived_Alert
1015 Voicemail.caf Voicemail.caf - Available since 2.1
1016 tweet_sent.caf tweet_sent.caf SMSSent Available since 5.0
1020 Anticipate.caf Anticipate.caf SMSReceived_Alert Available since 4.2
1021 Bloom.caf Bloom.caf SMSReceived_Alert Available since 4.2
1022 Calypso.caf Calypso.caf SMSReceived_Alert Available since 4.2
1023 Choo_Choo.caf Choo_Choo.caf SMSReceived_Alert Available since 4.2
1024 Descent.caf Descent.caf SMSReceived_Alert Available since 4.2
1025 Fanfare.caf Fanfare.caf SMSReceived_Alert Available since 4.2
1026 Ladder.caf Ladder.caf SMSReceived_Alert Available since 4.2
1027 Minuet.caf Minuet.caf SMSReceived_Alert Available since 4.2
1028 News_Flash.caf News_Flash.caf SMSReceived_Alert Available since 4.2
1029 Noir.caf Noir.caf SMSReceived_Alert Available since 4.2
1030 Sherwood_Forest.caf Sherwood_Forest.caf SMSReceived_Alert Available since 4.2
1031 Spell.caf Spell.caf SMSReceived_Alert Available since 4.2
1032 Suspense.caf Suspense.caf SMSReceived_Alert Available since 4.2
1033 Telegraph.caf Telegraph.caf SMSReceived_Alert Available since 4.2
1034 Tiptoes.caf Tiptoes.caf SMSReceived_Alert Available since 4.2
1035 Typewriters.caf Typewriters.caf SMSReceived_Alert Available since 4.2
1036 Update.caf Update.caf SMSReceived_Alert Available since 4.2
1050 ussd.caf ussd.caf USSDAlert
1051 SIMToolkitCallDropped.caf SIMToolkitCallDropped.caf SIMToolkitTone
1052 SIMToolkitGeneralBeep.caf SIMToolkitGeneralBeep.caf SIMToolkitTone
1053 SIMToolkitNegativeACK.caf SIMToolkitNegativeACK.caf SIMToolkitTone
1054 SIMToolkitPositiveACK.caf SIMToolkitPositiveACK.caf SIMToolkitTone
1055 SIMToolkitSMS.caf SIMToolkitSMS.caf SIMToolkitTone
1057 Tink.caf Tink.caf PINKeyPressed
1070 ct-busy.caf ct-busy.caf AudioToneBusy There was no category for this sound before 4.0.
1071 ct-congestion.caf ct-congestion.caf AudioToneCongestion There was no category for this sound before 4.0.
1072 ct-path-ack.caf ct-path-ack.caf AudioTonePathAcknowledge There was no category for this sound before 4.0.
1073 ct-error.caf ct-error.caf AudioToneError There was no category for this sound before 4.0.
1074 ct-call-waiting.caf ct-call-waiting.caf AudioToneCallWaiting There was no category for this sound before 4.0.
1075 ct-keytone2.caf ct-keytone2.caf AudioToneKey2 There was no category for this sound before 4.0.
1100 lock.caf sq_lock.caf ScreenLocked
1101 unlock.caf sq_lock.caf ScreenUnlocked
1102 - - FailedUnlock
1103 Tink.caf sq_tock.caf KeyPressed
1104 Tock.caf sq_tock.caf KeyPressed
1105 Tock.caf sq_tock.caf KeyPressed
1106 beep-beep.caf sq_beep-beep.caf ConnectedToPower
1107 RingerChanged.caf RingerChanged.caf RingerSwitchIndication
1108 photoShutter.caf photoShutter.caf CameraShutter
1109 shake.caf shake.caf ShakeToShuffle Available since 3.0
1110 jbl_begin.caf jbl_begin.caf JBL_Begin Available since 3.0
1111 jbl_confirm.caf jbl_confirm.caf JBL_Confirm Available since 3.0
1112 jbl_cancel.caf jbl_cancel.caf JBL_Cancel Available since 3.0
1113 begin_record.caf begin_record.caf BeginRecording Available since 3.0
1114 end_record.caf end_record.caf EndRecording Available since 3.0
1115 jbl_ambiguous.caf jbl_ambiguous.caf JBL_Ambiguous Available since 3.0
1116 jbl_no_match.caf jbl_no_match.caf JBL_NoMatch Available since 3.0
1117 begin_video_record.caf begin_video_record.caf BeginVideoRecording Available since 3.0
1118 end_video_record.caf end_video_record.caf EndVideoRecording Available since 3.0
1150 vc~invitation-accepted.caf vc~invitation-accepted.caf VCInvitationAccepted Available since 4.0
1151 vc~ringing.caf vc~ringing.caf VCRinging Available since 4.0
1152 vc~ended.caf vc~ended.caf VCEnded Available since 4.0
1153 ct-call-waiting.caf ct-call-waiting.caf VCCallWaiting Available since 4.1
1154 vc~ringing.caf vc~ringing.caf VCCallUpgrade Available since 4.1
1200 dtmf-0.caf dtmf-0.caf TouchTone
1201 dtmf-1.caf dtmf-1.caf TouchTone
1202 dtmf-2.caf dtmf-2.caf TouchTone
1203 dtmf-3.caf dtmf-3.caf TouchTone
1204 dtmf-4.caf dtmf-4.caf TouchTone
1205 dtmf-5.caf dtmf-5.caf TouchTone
1206 dtmf-6.caf dtmf-6.caf TouchTone
1207 dtmf-7.caf dtmf-7.caf TouchTone
1208 dtmf-8.caf dtmf-8.caf TouchTone
1209 dtmf-9.caf dtmf-9.caf TouchTone
1210 dtmf-star.caf dtmf-star.caf TouchTone
1211 dtmf-pound.caf dtmf-pound.caf TouchTone
1254 long_low_short_high.caf long_low_short_high.caf Headset_StartCall
1255 short_double_high.caf short_double_high.caf Headset_Redial
1256 short_low_high.caf short_low_high.caf Headset_AnswerCall
1257 short_double_low.caf short_double_low.caf Headset_EndCall
1258 short_double_low.caf short_double_low.caf Headset_CallWaitingActions
1259 middle_9_short_double_low.caf middle_9_short_double_low.caf Headset_TransitionEnd
1300 Voicemail.caf Voicemail.caf SystemSoundPreview
1301 ReceivedMessage.caf ReceivedMessage.caf SystemSoundPreview
1302 new-mail.caf new-mail.caf SystemSoundPreview
1303 mail-sent.caf mail-sent.caf SystemSoundPreview
1304 alarm.caf sq_alarm.caf SystemSoundPreview
1305 lock.caf sq_lock.caf SystemSoundPreview
1306 Tock.caf sq_tock.caf KeyPressClickPreview The category was SystemSoundPreview before 3.2.
1307 sms-received1.caf sms-received1.caf SMSReceived_Selection
1308 sms-received2.caf sms-received2.caf SMSReceived_Selection
1309 sms-received3.caf sms-received3.caf SMSReceived_Selection
1310 sms-received4.caf sms-received4.caf SMSReceived_Selection
1311 - - SMSReceived_Vibrate
1312 sms-received1.caf sms-received1.caf SMSReceived_Selection
1313 sms-received5.caf sms-received5.caf SMSReceived_Selection
1314 sms-received6.caf sms-received6.caf SMSReceived_Selection
1315 Voicemail.caf Voicemail.caf SystemSoundPreview Available since 2.1
1320 Anticipate.caf Anticipate.caf SMSReceived_Selection Available since 4.2
1321 Bloom.caf Bloom.caf SMSReceived_Selection Available since 4.2
1322 Calypso.caf Calypso.caf SMSReceived_Selection Available since 4.2
1323 Choo_Choo.caf Choo_Choo.caf SMSReceived_Selection Available since 4.2
1324 Descent.caf Descent.caf SMSReceived_Selection Available since 4.2
1325 Fanfare.caf Fanfare.caf SMSReceived_Selection Available since 4.2
1326 Ladder.caf Ladder.caf SMSReceived_Selection Available since 4.2
1327 Minuet.caf Minuet.caf SMSReceived_Selection Available since 4.2
1328 News_Flash.caf News_Flash.caf SMSReceived_Selection Available since 4.2
1329 Noir.caf Noir.caf SMSReceived_Selection Available since 4.2
1330 Sherwood_Forest.caf Sherwood_Forest.caf SMSReceived_Selection Available since 4.2
1331 Spell.caf Spell.caf SMSReceived_Selection Available since 4.2
1332 Suspense.caf Suspense.caf SMSReceived_Selection Available since 4.2
1333 Telegraph.caf Telegraph.caf SMSReceived_Selection Available since 4.2
1334 Tiptoes.caf Tiptoes.caf SMSReceived_Selection Available since 4.2
1335 Typewriters.caf Typewriters.caf SMSReceived_Selection Available since 4.2
1336 Update.caf Update.caf SMSReceived_Selection Available since 4.2
1350 - - RingerVibeChanged
1351 - - SilentVibeChanged
4095 - - Vibrate There was no category for this sound before 2.2.In the SDK this is the constant kSystemSoundID_Vibrate
  • 播放自定义铃声

首先把要播放的音频文件放到工程里,Bundle读取url之后,用AudioServicesCreateSystemSoundID方法获取我们这个音频注册之后的SystemSoundID,就可以用AudioServicesPlaySystemSound直接播放出来了,这里我们假定播放注册一个名为“sound.m4a”的音频文件

var soundId: SystemSoundID = SystemSoundID()
let path = Bundle.main.path(forResource: "sound", ofType: "m4a")
let url = URL.init(fileURLWithPath: path!)
AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
AudioServicesPlaySystemSound(soundId)
  • 循环播放

@available(iOS 2.0, *)
public func AudioServicesAddSystemSoundCompletion(_ inSystemSoundID: SystemSoundID, _ inRunLoop: CFRunLoop?, _ inRunLoopMode: CFString?, _ inCompletionRoutine: @escaping AudioToolbox.AudioServicesSystemSoundCompletionProc, _ inClientData: UnsafeMutableRawPointer?) -> OSStatus

使用AudioServicesAddSystemSoundCompletion方法,可以为一个SystemSoundID绑定一个播放完成之后的回调,我们可以在回调里继续播放这个SystemSoundID,播放后会继续回到回调,这样就做到了循环播放的效果,记住,这个方法是全局的,如果你为一个SystemSoundID绑定过回调之后,不取消的话,其他地方播放这个SystemSoundID也会进入回调,所以停止播放时记得用AudioServicesRemoveSystemSoundCompletion方法移除回调绑定。至于停止播放,使用AudioServicesDisposeSystemSoundID方法传入SystemSoundID就可以了。全部的示例代码看下面

    var soundId: SystemSoundID?

    //注册音频文件,获取SystemSoundID
    func getSoundId() -> SystemSoundID {
        
        var soundId: SystemSoundID = SystemSoundID()
        let path = Bundle.main.path(forResource: "sound", ofType: "m4a")
        let url = URL.init(fileURLWithPath: path!)
        AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
        return soundId
        
    }
    
    //播放自定义铃声和震动
    func playAlertSound() {
        
        if soundId == nil {
            soundId = self.getSoundId()
        }
        
        AudioServicesAddSystemSoundCompletion(soundId!, nil, nil, { (SystemSoundID, pointer: UnsafeMutableRawPointer?) in

            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
            AudioServicesPlaySystemSound(SystemSoundID)

        }, nil)
        //kSystemSoundID_Vibrate是震动的id
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        AudioServicesPlaySystemSound(soundId!)
        
    }
    
    //停止播放
    func stopAlertSoundWithSoundID() {
        
        if soundId != nil {
            AudioServicesDisposeSystemSoundID(soundId!)
            AudioServicesRemoveSystemSoundCompletion(soundId!)
            soundId = nil
        }
        
        AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate)
        
    }

欢迎更正错误和交流,回复评论和私信皆可 😊

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343