Can't play file from documents in AVAudioPlayer

前端 未结 1 1228
天涯浪人
天涯浪人 2021-01-24 17:42

I have a file on documents folder of app and I want to play it.

if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
    let url = NSURL(fileURLWith         


        
相关标签:
1条回答
  • 2021-01-24 18:34

    You should make audioPlayer an instance variable global. This code will have it deallocated immediately after calling .play()

    class ViewController: UIViewController {
    
        var audioPlayer = AVAudioPlayer()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            if NSFileManager.defaultManager().fileExistsAtPath(pathString){
            let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
            AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
            AVAudioSession.sharedInstance().setActive(true, error: nil)
    
            var error:NSError?
            audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题