先將資源文件添加到工程中,如下代碼為播放代碼
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK:- 音效播放
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("開始播放音效")
//1.獲取systemSoundId:Creates a system sound object.
let url = Bundle.main.url(forResource: "m_17.wav", withExtension: nil)
let urlCF = url! as CFURL
//1.1 創(chuàng)建SystemSoundId
var soundID : SystemSoundID = 0
AudioServicesCreateSystemSoundID(urlCF, &soundID)
//2.根據soundId,播放音效
//帶有震動播放效果
// AudioServicesPlayAlertSound(soundID)
//不帶有震動播放
//AudioServicesPlaySystemSound(soundID)
//帶有回調函數的播放
AudioServicesPlaySystemSoundWithCompletion(soundID) {
//3.根據soundId东跪,釋放音效
print("根據soundId倦春,釋放音效")
AudioServicesDisposeSystemSoundID(soundID)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print("結束播放音效")
}
}
封裝后的音頻播放方法
// Audio_Extension.swift
import UIKit
import AVFoundation
//類方法
class AudioTool: NSObject {
class func audioPlay(audioName:String,isAlert:Bool,inCompletion:@escaping ()->()){
//1.獲取systemSoundId:Creates a system sound object.
let url = Bundle.main.url(forResource: audioName, withExtension: nil)
let urlCF = url! as CFURL
//1.1 創(chuàng)建SystemSoundId
var soundID : SystemSoundID = 0
AudioServicesCreateSystemSoundID(urlCF, &soundID)
//2.根據soundId,播放音效
if isAlert {
AudioServicesPlayAlertSoundWithCompletion(soundID) {
//3. 根據soundId,釋放音效
AudioServicesDisposeSystemSoundID(soundID)
//4.告訴外界播放完成的事件
inCompletion()
}
}else {
AudioServicesPlaySystemSoundWithCompletion(soundID) {
//3.根據soundId黔宛,釋放音效
AudioServicesDisposeSystemSoundID(soundID)
//4.告訴外界播放完成的事件
inCompletion()
}
}
}
}
外界調用
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("開始播放音效")
AudioTool.audioPlay(audioName: "m_17.wav", isAlert: false) {
print("成功釋放")
}
}