先将资源文件添加到工程中,如下代码为播放代码
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 创建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 创建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("成功释放")
}
}