简体   繁体   中英

Play audio and vibration simultaneously on ios using swift

Is there any way to play audio file and vibrate iphone when audio is started and stop vibrating when audio stops playing?

currently this code is working but it plays audio and when audio stops then it vibrates the phone, I want both (audio and vibration) play together.

var alertSoundEffect: AVAudioPlayer?

let path = Bundle.main.path(forResource: "alert.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
    alertSoundEffect = try AVAudioPlayer(contentsOf: url)
    alertSoundEffect?.prepareToPlay()
    alertSoundEffect?.play()
} catch {
    return
}

let vib = SystemSoundID(1519)
AudioServicesPlayAlertSound(SystemSoundID(vib))
AudioServicesRemoveSystemSoundCompletion(vib)

You can try

 DispatchQueue.global().async 
 {
      var alertSoundEffect: AVAudioPlayer?

      let path = Bundle.main.path(forResource: "alert.mp3", ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            alertSoundEffect = try AVAudioPlayer(contentsOf: url)
            alertSoundEffect?.prepareToPlay()
            alertSoundEffect?.play()
        } catch {
            return
        }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM