AVPlayer 播放在线资源但不播放相同的下载资源
AVPlayer plays online resource but not same downloaded resource
我从服务器下载了一个音频文件到我的文档目录。我正在尝试在 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 播放本地文件?
您应该使用 fileURLWithPath: 来提供正确的 url,它应该可以很好地播放本地 url。
let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: localAudioPath!)!)
我从服务器下载了一个音频文件到我的文档目录。我正在尝试在 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 播放本地文件?
您应该使用 fileURLWithPath: 来提供正确的 url,它应该可以很好地播放本地 url。
let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: localAudioPath!)!)