ios - 使用 AVPlayer 播放下载到文件管理器的 mp3 文件

标签 ios swift swift3 avplayer nsfilemanager

我正在 swift3 做一个项目我有一个特定的 UIViewController 可以将 mp3 下载到我的文件管理器并使用保存的路径我想使用 AVPlayer 播放 mp3。我的代码不起作用,我想我遗漏了一些东西。我将如何实现这一目标?我的代码将文件下载到文件管理器,如下所示

func downloadSong() {

    if let audioUrl = URL(string: "https://www.googleapis.com/download/storage/v1/b/feisty-beacon-159305.appspot.com/o/Aal%20Izz%20Well%20-%20Remix(MyMp3Song).mp3?generation=1490097740630162&alt=media") {

        // then lets create your document folder url
        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!//since it sys first this may  only plays the first item

        // destination file url
        let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
        print("destinationUrl is :",destinationUrl)

        // to check if it exists before downloading it
        if FileManager.default.fileExists(atPath: destinationUrl.path) {
            print("The file already exists at path")
             self.dest = destinationUrl.path
            // if the file doesn't exist
        } else {

            // you can use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void 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 path is :",destinationUrl.path)
                    print("File moved to documents folder")
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }).resume()
        }
    }
}

一旦我保存了该文件,使用它的文件路径“destinationUrl.path”,我在不同的 UIViewController 中启动我的播放器,如下所示。至于现在我已经硬编码了我保存的路径。代码如下。

    override func viewDidLoad() {
        super.viewDidLoad()
    //path I have saved in file manager is set to the url
    let url = NSURL.fileURL(withPath:"/Users/auxenta/Library/Developer/CoreSimulator/Devices/F3840294-04AA-46BE-9E46-4342452AFB69/data/Containers/Data/Application/670C0EA1-B375-498E-8847-8707D391D7BF/Documents/Aal Izz Well - Remix(MyMp3Song).mp3") as NSURL

        self.playerItem = AVPlayerItem(url: url as URL)
        self.player=AVPlayer(playerItem: self.playerItem!)
        let playerLayer=AVPlayerLayer(player: self.player!)
        playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
        self.view.layer.addSublayer(playerLayer)
    }

@IBAction func playBtnPressed(_ sender: Any) {
         if player?.rate == 0 // this means if its not playing
         {
            player!.play()
            print("playing")
            playbutton.setImage(UIImage(named: "pausebutton"), for: UIControlState.normal)

            //trackTime
            trackTime()
       } else {
            // getFileFromFieManager()
            print("pause")
            player!.pause()
            playbutton.setImage(UIImage(named: "playbutton"), for: UIControlState.normal)
      }

}

最佳答案

您的问题是设置给 AVPlayer 的 URL。事实上,在 iOS 中硬编码路径是行不通的,它可以随时更改。

您需要像使用 destinationUrl 一样使用代码:

    if let audioUrl = URL(string: "https://www.googleapis.com/download/storage/v1/b/feisty-beacon-159305.appspot.com/o/Aal%20Izz%20Well%20-%20Remix(MyMp3Song).mp3?generation=1490097740630162&alt=media") {
                
                
          let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!//since it sys first this may  only plays the first item
                
           // destination file url
           let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
           print("destinationUrl is :",destinationUrl)
            
           self.playerItem = AVPlayerItem(url: destinationUrl)
           self.player=AVPlayer(playerItem: self.playerItem!)
           let playerLayer=AVPlayerLayer(player: self.player!)
  

                         .
                         .
                         .
}

正常情况下它应该可以工作。希望对您有所帮助。

关于ios - 使用 AVPlayer 播放下载到文件管理器的 mp3 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944294/

相关文章:

ios - 基于 Xcode 构建配置的应用程序传输层安全性

ios - 在 NSUserDefaults 中保存自定义 NSObject

ios - 单击或点击时 View Controller 中的元素消失

Swift:我如何等到变量具有特定值

swift - 在 Interface Builder 中设计自定义 View

ios - 在 AppDelegate 中更改 Root View Controller 时出现黑屏

iOS - 在应用程序外触发点击事件 - 比如在应用程序抽屉中

ios - 如何/是否在 Xcode 中制作通用 Storyboard

ios - 带有附加对象的 NSFetchedResultsController

ios - 为什么不调用 MKMapView 中的 clusterAnnotationForMemberAnnotations?