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

Play an mp3 file downloaded to filemanager using AVPlayer

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

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)
      }

}

您可以使用下面的代码。我希望我能帮助你。首先你需要为你想要播放的源文件创建路径

 let path = Bundle.main.path(forResource: "yourFileName", ofType: "mp3")
        let soundUrl = URL(fileURLWithPath: path!)

        do{

            try btnSound = AVAudioPlayer(contentsOf: soundUrl)
            btnSound.prepareToPlay()
        }
        catch let err as NSError{

        print(err.debugDescription)


        }

在您在 viewDidLoad 方法中创建这些之后。您可以为播放声音创建功能,例如;

func playSound() {

       if btnSound.isPlaying {
         btnSound.stop()
        }

        btnSound.play()

    }

完成所有这些后,您就可以播放 swift 中的 mp3 文件了。

您的问题是 URL 设置为 AVPlayer。事实上,在 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!)
  

                         .
                         .
                         .
}

正常情况下应该可以。希望对你有帮助。