我有一个从服务器下载到我的文档目录的音频文件。我试图在swift中使用AVPlayer同样玩,但有些原因无法这样做。以下是我的整个代码。如果我们将localAudioPath
替换为onlineResource
则可以正常
import UIKit
import AVFoundation
class AudioController: UIViewController {
var player : AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func playAudio(sender: AnyObject) {
var name = "bell.mp3"
var docs = NSSearchPathForDirectoriesInDomains(directory, .UserDomainMask, true)[0] as! String
var localAudioPath = docs.stringByAppendingPathComponent(name)
var onlineResource = "path/to/online/bell.mp3"
if NSFileManager.defaultManager().fileExistsAtPath(localAudioPath!) {
let playerItem = AVPlayerItem(URL: NSURL(string: localAudioPath!)!)
player = AVPlayer(playerItem: playerItem)
player.play()
} else {
/* Alamo fire code to download file to docs directory*/
let destination = Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, NSURL(string: audio.audioUrl)!.http, destination)
.progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
println(totalBytesRead)
}
.response { (request, response, _, error) in
println(response)
}
}
}
}
有人可以告诉我,甚至可以使用AVPlayer播放本地文件吗?
答案 0 :(得分:1)
您应该使用fileURLWithPath:提供正确的网址,它应该播放本地网址就好了。
let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: localAudioPath!)!)