我想播放一个下载的本地音频文件,但是它无法播放:
class AVPlayerService {
static let instance = AVPlayerService()
private var audioPlayer: AVPlayer!
public weak var delegate: AVPlayerServiceDelegate?
func setupPlayer(forURL url: URL) {
let playerItem: AVPlayerItem = AVPlayerItem(url: URL(fileURLWithPath: "\(url)")
audioPlayer = AVPlayer(playerItem: playerItem)
audioPlayer.play()
}
我在这里获取本地文件,然后在我的视图控制器中调用它:
func getDownloadedSurahFor(surah: Surah, reciter: Reciter) -> (Exists, URL?) {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(reciter.name): \(surah.number)")
print(destinationUrl)
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("Already downloaded")
return (.exists, destinationUrl)
} else {
return (.doesNotExist, nil)
}
}
在我的 Viewcontroller 中,我检查它是否存在,然后调用 setupPlayer:。
let (exists, url) = DataService.instance.getDownloadedSurahFor(surah: playingSurah, reciter: reciter)
if exists == .exists {
self.audioService.setupPlayer(forURL: url!)
self.setupSlider()
self.changeButtonTo(.pause)
print("Downloaded file should now play")
}