1

I have two sounds (ping and alarm) that should be played when the respective conditions are fulfilled. Both sounds are played repeatedly. It is possible that both sounds overlap with each other, which is why I declared a separate AVAudioPlayer to play each sound (pingPlayer and alarmPlayer).

  1. Type of freeze: Ping and alarm play properly on their own, but when both are activated, the whole app freezes at the beginning.

  2. Type of freeze: When only the alarm is activated with additional pause or stop statements in the code, the app freezes as well.

import AVFoundation

private var pingPlayer: AVAudioPlayer?
private var alarmPlayer: AVAudioPlayer?

func playPing() {
        guard let url = Bundle.main.url(forResource: "ping", withExtension: "mp3") else { return }
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
            pingPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            guard let player = pingPlayer else { return }

            player.play()
        } catch let error {
            print(error.localizedDescription)
        }
    }

alarmPlayer is initialised in viewDidLoad() Because when the alarmPlayer is initialised in a separate function (like playPing()), the app still freezes.

override viewDidLoad() {
//...

    guard let url = Bundle.main.url(forResource: "alarm", withExtension: "mp3") else { return }
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
            alarmPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        } catch let error {
            print(error.localizedDescription)
        }
    }

//alarmPlayer is then called after the condition like this: 

alarmPlayer?.prepareToPlay()
alarmPlayer?.play()
  1. Type of freeze: called after a certain condition is fulfilled
alarmPlayer?.stop() //or alarmPlayer?.pause()
agimus
  • 33
  • 4
  • Why do you use two instances of AVAudioPlayer and not one? – Tal Cohen Jun 25 '19 at 15:21
  • Its likely because although `AVAudioPlayer` supports multiple instances to play several sounds at once, it appears they may have to be initialized at the same time. Maybe this answer can provide you some insight. https://stackoverflow.com/a/36865967/6448167 – KSigWyatt Jun 25 '19 at 20:56

0 Answers0