无法播放AVAudioPlayer中文档中的文件 [英] Can't play file from documents in AVAudioPlayer
本文介绍了无法播放AVAudioPlayer中文档中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在应用程序的文档文件夹中有一个文件,我想播放它.
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 {}
}
文件系统上有一个文件,我检查了它的存在.同时执行do块中的所有行.既没有异常也没有错误,并且仍然没有声音播放.有什么可能的问题,我该如何解决?
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?
推荐答案
您应将audioPlayer设置为全局实例变量.调用.play()
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()
}
}
}
这篇关于无法播放AVAudioPlayer中文档中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文