swift 下载歌曲数据然后从文件播放

p8h8hvxi  于 2023-04-28  发布在  Swift
关注(0)|答案(1)|浏览(151)

我正在尝试从歌曲链接下载数据,将其保存到文件,然后从文件播放。Breakpoint没有在catch block上运行,但我听不到音乐。我的代码有什么问题?

override func viewDidLoad() {
    let url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
    downloadSong(url: url)
}

func downloadSong(url: String) {
    guard let url = URL(string: url) else { return }
    let request = URLRequest(url: url)
    session.dataTask(with: request) { data, response, error in
        if let data = data {
            DispatchQueue.main.async {
                self.savedFiles[url.absoluteString] = data
                self.playAudio(fromData: data, url: url)
            }
        }
    }.resume()
}

func playAudio(fromData audioData: Data, url: URL) {
    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let audioFileURL = documentsDirectoryURL.appendingPathComponent(url.lastPathComponent)
    
    do {
        try audioData.write(to: audioFileURL)
        DispatchQueue.main.async {
            let audioPlayerItem = AVPlayerItem(url: audioFileURL)
            let audioPlayer = AVPlayer(playerItem: audioPlayerItem)
            audioPlayer.play()
        }
    } catch {
        print("Error writing audio data to file: \(error.localizedDescription)")
    }
}
<key>NSFileProviderExtension</key>
<array>
    <dict>
        <key>NSFileProviderWritable</key>
        <true/>
    </dict>
</array>

我设置了这个权限。

pqwbnv8z

pqwbnv8z1#

将AVPlayer设置为视图控制器类变量。在DispatchQueue块完成后,在代码播放器中初始化

let audioPlayer = AVPlayer()
func playAudio(fromData audioData: Data, url: URL) {
    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let audioFileURL = documentsDirectoryURL.appendingPathComponent(url.lastPathComponent)
    
    do {
        try audioData.write(to: audioFileURL)
        DispatchQueue.main.async { [weak audioPlayer] in
            let audioPlayerItem = AVPlayerItem(url: audioFileURL)
            audioPlayer?.replaceCurrentItem(with: audioPlayerItem)
            audioPlayer?.play()
        }
    } catch {
        print("Error writing audio data to file: \(error.localizedDescription)")
    }
}

相关问题