简体   繁体   中英

Swift AVAudioPlayer's playing status always be true?

Here's my code:

@objc func playSmusic1() {
        guard let url = Bundle.main.url(forResource: "Snote6", withExtension: "wav") else { return }
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
            guard let player = player else { return }
            while (true) {
                player.play()
                player.enableRate = true;
                player.rate = playrate
                if !player.isPlaying {
                    break
                }
            }
        } catch let error {
            print(error.localizedDescription)
        }
    }

I found player.isPlaying properties always be true, so sometimes a tone will be play for 2 or 3 times. How to fix this bug? Thanks a lot!

First: Don't use while(true) for checking because it blocks the main thread !

You should add KVO observer to check this property asynchronously eg:

class YourController : UIViewController {
    var player: AVAudioPlayer?
    //...
    
    deinit {
        player?.removeObserver(self, forKeyPath: #keyPath(AVAudioPlayer.isPlaying))
    }

    func play() {
        //...
        player?.addObserver(self,
            forKeyPath: #keyPath(AVAudioPlayer.isPlaying),
            options: .new,
            context: nil)
        player?.play()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(AVAudioPlayer.isPlaying) {
            if let isPlaying = player?.isPlaying {
                print(isPlaying)
            }
        }
        else {
            self.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}

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