Play a short sound in iOS

前端 未结 13 827
悲哀的现实
悲哀的现实 2020-11-27 10:23

I guess I could use AVAudioPlayer to play a sound, however, what I need is to just play a short sound and I don\'t need any loops or fine-grained control over t

13条回答
  •  北海茫月
    2020-11-27 11:08

    SIMPLE CLEAN SWIFT 3 VERSION

    I like more control over my sounds so I'm using AVFoundation.

    import AVFoundation
    
    class TodayViewController: UIViewController {
    
      var clink: AVAudioPlayer?
      var shatter: AVAudioPlayer?
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        // initialize the sound
        shatter = setupAudioPlayer(withFile: "shatter", type: "wav")
        clink = setupAudioPlayer(withFile: "clink", type: "wav")
      }
    
      func setupAudioPlayer(withFile file: String, type: String) -> AVAudioPlayer? {
        let path = Bundle.main.path(forResource: file, ofType: type)
        let url = NSURL.fileURL(withPath: path!)
        return try? AVAudioPlayer(contentsOf: url)
      }
    
      func onClick() {
        clink?.play()
      }
    }
    

    Make sure you sound file is added to your project and you import AVFoundation.

提交回复
热议问题