繁体   English   中英

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

[英]Play an mp3 file downloaded to filemanager using AVPlayer

我正在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!)
  

                         .
                         .
                         .
}

通常它应该工作。 希望能帮助到你。

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

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

    }

在所有这些之后,您可以快速播放 mp3 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM