iOS开发 本地音效播放 SoundManager

官方提供了AudioToolbox框架,可以用来播放短音效。
① 播放的时间不能超过30秒
② 声音文件须放到设备的本地文件夹目录下

比如在一些交互中,要使用不同音效时候,可以封装成一个类,方便调用。

iOS开发 本地音效播放 SoundManager_第1张图片
SoundManager
SoundManager.swift
import UIKit
import AudioToolbox //导入框架

class SoundManager {
    
    var soundId:SystemSoundID = 0

    enum SoundType {
        case doo, re, mi, fa, so, la, se
    }

    func loadaudioFile(soundType: SoundType) {
        var sound = (name:"error", type:"wav")
        switch soundType {
        case .doo:
            sound = (name:"doo", type:"wav")
        case .re:
            sound = (name:"re", type:"wav")
        case .mi:
            sound = (name:"mi", type:"mp3")
        case .fa:
            sound = (name:"fa", type:"wav")
        case .so:
            sound = (name:"so", type:"wav")
        case .la:
            sound = (name:"la", type:"wav")
        case .se:
            sound = (name:"se", type:"wav")
        }
        let soundUrl =  NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource(sound.name, ofType: sound.type)!)
        AudioServicesCreateSystemSoundID(soundUrl, &soundId)  
    }
    
    func playSound() {
        AudioServicesPlaySystemSound(soundId)
        // 震动
        //AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
    }
}

使用:
    let sound = SoundManager() //跟哥们联系
    sound.loadaudioFile(SoundManager.SoundType.doo) //取到指定音频
    sound.playSound() //播放音频

你可能感兴趣的:(iOS开发 本地音效播放 SoundManager)