swift5 音频播放SoundID

//
//  AudioTool.swift
//  ReconderSuccess1
//
//  Created by lujun on 2022/1/27.
//

import UIKit
import AVFoundation

class AudioTool: NSObject {
    class func playAudio(audioName: String, isAlert: Bool = false,
                         finishedCallback: @escaping () -> () ) {
        guard  let url = Bundle.main.url(forResource: audioName, withExtension: nil) else {
            return
        }
        let urlCF = url as CFURL
        var soundID: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(urlCF, &soundID)
        
        if isAlert {
            AudioServicesPlayAlertSoundWithCompletion(soundID) {
                AudioServicesDisposeSystemSoundID(soundID)
            }
            finishedCallback()
        }else {
            AudioServicesPlaySystemSoundWithCompletion(soundID) {
                //释放
                AudioServicesDisposeSystemSoundID(soundID)
                finishedCallback()
            }
        }
    }
    
}

VC controller 里面的东西
```
//
// SoundPlayerAudioToolVC.swift
// ReconderSuccess1
//
// Created by lujun on 2022/1/27.
//

import UIKit

class SoundPlayerAudioToolVC: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    debugPrint(#file)
    debugPrint(#line)
    debugPrint(#filePath)
    debugPrint(#function)
}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
    AudioTool.playAudio(audioName: "32D81EBC-73CB-4436-923E-340DB3B316AC.caf") {
         debugPrint("播放完成")
    }
    
}

}

posted @ 2022-01-27 17:33  johnson--save  阅读(190)  评论(0)    收藏  举报