播放使用AVPlayer下载到filemanager的mp3文件

时间:2017-03-22 06:31:54

标签: ios swift swift3 avplayer nsfilemanager

我正在研究swift3中的一个项目,我有一个特定的UIViewController将mp3下载到我的文件管理器并使用该路径保存我想使用AVPlayer播放mp3 。我的代码不起作用,我想我错过了一些东西。我怎么做到这一点?我的代码将文件下载到filemanager,如下所示

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

}

2 个答案:

答案 0 :(得分:2)

您的问题是安装到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!)


                         .
                         .
                         .
}

通常应该有效。希望它有所帮助。

答案 1 :(得分:0)

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

 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文件了。