gpt4 book ai didi

ios - 如何播放应用程序中下载的音频文件?

转载 作者:行者123 更新时间:2023-11-30 12:35:05 25 4
gpt4 key购买 nike

我想知道如何播放在应用程序中下载的文件,我下载了一个音乐文件然后我想在应用程序中播放它,我找到了这个函数并用它来下载。非常感谢。

func downloadSong (_ sender:UIButton) {
if let url = URL(string: startURL) {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(url.lastPathComponent)
print(destinationUrl)

// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")

// if the file doesn't exist
} else {
print("Downloading started")

// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: url, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
print("Downloading finished")

do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: destinationUrl)
print("File moved to documents folder")
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
}
}

最佳答案

使用您的目标网址尝试 AVAudioPlayer

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:destinationUrl error:nil];
player.numberOfLoops = -1;
[player play];

Swift 版本:

let player = try? AVAudioPlayer(contentsOf: destinationUrl)
player?.numberOfLoops = -1;
player?.play()

关于ios - 如何播放应用程序中下载的音频文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com