保存 .mp3 以快速离线播放

发布于 2025-01-13 04:57:20 字数 2096 浏览 2 评论 0原文

我正在尝试保存从 url 下载的 .mp3,显然我保存了该文件,但在播放时,仅使用 deebug 我就可以听它 5 秒钟。

 func saveAudioLocally(fileName: String, name: String, guideNumber: String){
    if let audioUrl = URL(string: fileName) {

        // 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("\(name)_\(guideNumber)")
        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 {

            // you can use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: audioUrl) { location, response, error in
                guard let location = location, error == nil else { return }
                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")
                    print(destinationUrl)
                } catch {
                    print(error)
                }
            }.resume()
        }
    }
}

播放我正在使用的音频

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                url = documentsDirectory.appendingPathComponent("\(self.track.name)_\(self.track.idTrackNavigation.guideNumber)")
                
                do {
                    let audioPlayer = try AVAudioPlayer(contentsOf: url!)                                
                    audioPlayer.prepareToPlay()
                    audioPlayer.play()
                } catch let error {
                    print(error.localizedDescription)
                }

I am trying to save an .mp3 that I download from a url, apparently I save the file but at the moment of playing in, just with deebug I could listen to it for 5 seconds.

 func saveAudioLocally(fileName: String, name: String, guideNumber: String){
    if let audioUrl = URL(string: fileName) {

        // 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("\(name)_\(guideNumber)")
        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 {

            // you can use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: audioUrl) { location, response, error in
                guard let location = location, error == nil else { return }
                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")
                    print(destinationUrl)
                } catch {
                    print(error)
                }
            }.resume()
        }
    }
}

To play the audio I'm using

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                url = documentsDirectory.appendingPathComponent("\(self.track.name)_\(self.track.idTrackNavigation.guideNumber)")
                
                do {
                    let audioPlayer = try AVAudioPlayer(contentsOf: url!)                                
                    audioPlayer.prepareToPlay()
                    audioPlayer.play()
                } catch let error {
                    print(error.localizedDescription)
                }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

属性 2025-01-20 04:57:20

让我知道这是否适合您。

import UIKit
import AVFoundation

class ViewController: UIViewController, URLSessionDelegate, URLSessionDownloadDelegate {

   override func viewDidLoad() {
       super.viewDidLoad()
       
       let audio = "http://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Kangaroo_MusiQue_-_The_Neverwritten_Role_Playing_Game.mp3"
       download(name: "audio.mp3", url: audio)
       
   }
   
  
   func download(name: String, url: String) {
       filename = name
       let downloadURL = URL(string: url)!
       
       let config = URLSessionConfiguration.default
       let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
       session.downloadTask(with: downloadURL).resume()
   }
   
   
   var filename = String()
   func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
       if let data = try? Data(contentsOf: location) {
               
               do {
                   try data.write(to: path(name: filename)!)
                   play(path: path(name: filename)!)
               }
               catch {}
       } else {}
   }
   
   

   var player: AVPlayer?
   var playerItem: AVPlayerItem?
   
   func play(path: URL) {
       playerItem = AVPlayerItem(url: path)
       player = AVPlayer(playerItem: playerItem)
       player?.play()
   }
 
   
   func path(name: String) -> URL? {
       let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
       return path?.appendingPathComponent(name)
   }
}

用它来检查文件是否存在。

func check(name: String) -> Bool {
        do {
            if try path(name: name)!.checkResourceIsReachable() { return true }
            else { return false }
        }
        catch { return false }
    }

使用:

    if check(name: filename) {
            // File exists
        }
        else {
            // File doesn't exist
        }

Let me know if this works for you.

import UIKit
import AVFoundation

class ViewController: UIViewController, URLSessionDelegate, URLSessionDownloadDelegate {

   override func viewDidLoad() {
       super.viewDidLoad()
       
       let audio = "http://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Kangaroo_MusiQue_-_The_Neverwritten_Role_Playing_Game.mp3"
       download(name: "audio.mp3", url: audio)
       
   }
   
  
   func download(name: String, url: String) {
       filename = name
       let downloadURL = URL(string: url)!
       
       let config = URLSessionConfiguration.default
       let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
       session.downloadTask(with: downloadURL).resume()
   }
   
   
   var filename = String()
   func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
       if let data = try? Data(contentsOf: location) {
               
               do {
                   try data.write(to: path(name: filename)!)
                   play(path: path(name: filename)!)
               }
               catch {}
       } else {}
   }
   
   

   var player: AVPlayer?
   var playerItem: AVPlayerItem?
   
   func play(path: URL) {
       playerItem = AVPlayerItem(url: path)
       player = AVPlayer(playerItem: playerItem)
       player?.play()
   }
 
   
   func path(name: String) -> URL? {
       let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
       return path?.appendingPathComponent(name)
   }
}

Use this to check if the file exists.

func check(name: String) -> Bool {
        do {
            if try path(name: name)!.checkResourceIsReachable() { return true }
            else { return false }
        }
        catch { return false }
    }

Use of:

    if check(name: filename) {
            // File exists
        }
        else {
            // File doesn't exist
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文