這是我的快速課程
import Foundation
import AVFoundation
class MusicPlayer{
static let shared = MusicPlayer()
var audioPlayer: AVAudioPlayer?
func startBackgroundMusic(backgroundMusicFileName: String) {
if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
let backgroundMusic = NSURL(fileURLWithPath: bundle)
do {
audioPlayer = try AVAudioPlayer(contentsOf:backgroundMusic as URL)
guard let audioPlayer = audioPlayer else { return }
audioPlayer.numberOfLoops = -1
audioPlayer.volume = 1.0
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
func stopBackgroundMusic() {
guard let audioPlayer = audioPlayer else { return }
audioPlayer.stop()
}
}
而且,這是我的 Controller 類的代碼
func downloadUsingAlamofire() {
let audioUrl = URL(string:"https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3")
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(
audioUrl!,
method: .get,
parameters: nil,
encoding: URLEncoding.default,
headers: nil,
to: destination).downloadProgress(closure: { (progress) in
}).response(completionHandler: { (DefaultDownloadResponse) in
let imageURL = fetchPathinDirectory(filepath:audioUrl!.lastPathComponent)
MusicPlayer.shared.startBackgroundMusic(backgroundMusicFileName: imageURL.path)
})
}
uj5u.com熱心網友回復:
正如評論中所解釋的那樣;
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
這意味著該檔案已下載到您的應用程式的檔案目錄中。但是當你閱讀檔案時:
if let bundle = Bundle.main.path(forResource: backgroundMusicFileName, ofType: "mp3") {
let backgroundMusic = NSURL(fileURLWithPath: bundle)
您在應用程式包中讀取檔案,這是您的應用程式及其資源(故事板、xib 等)的安裝位置。您必須從檔案目錄中讀取檔案。就像是 :
var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let downloadedFileUrl = documentsURL.appendingPathComponent(backgroundMusicFileName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326247.html
