Hafiz Shoaib Awan
Hafiz Shoaib Awan

Reputation: 302

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)

Upvotes: 1

Views: 1558

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

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
        }

 }

Upvotes: 1

Related Questions