如何防止两个重叠的AVAudioPlayers冻结应用程序?

时间:2019-06-25 15:12:44

标签: ios swift avfoundation avaudioplayer

当满足各自的条件时,我应该播放两种声音(ping和警报)。两种声音都反复播放。 两种声音可能会相互重叠,这就是为什么我声明了一个单独的AVAudioPlayer播放每种声音(pingPlayer和alarmPlayer)的原因。

  1. 冻结类型: Ping和警报可以单独正常播放,但是同时激活它们后,整个应用程序一开始就会冻结。

  2. 冻结类型: 当仅在代码中使用其他暂停或停止语句激活警报时,该应用程序也会冻结。

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在viewDidLoad()中初始化 因为在单独的功能(如playPing())中初始化alarmPlayer时,该应用程序仍会冻结。

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. 冻结类型: 满足特定条件后调用
alarmPlayer?.stop() //or alarmPlayer?.pause()

0 个答案:

没有答案