Can't play file from documents in AVAudioPlayer

霸气de小男生 提交于 2019-12-02 07:59:00

问题


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

if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
    let url = NSURL(fileURLWithPath:pathString, isDirectory: false)
    do {
        let player = try AVAudioPlayer(contentsOfURL:url)
        player.prepareToPlay()
        player.play()
    }
    catch let error as NSException {
        print(error)
    }
    catch {}
}

There is a file on file system and I checked its existence. Also all lines in do block are executed. There is neither exception nor error and still no sound is played. What are possible problems and how can I solve them?


回答1:


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()
    }
}
}


来源:https://stackoverflow.com/questions/38152314/cant-play-file-from-documents-in-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!