首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用mp3播放下载到filemanager的AVPlayer文件

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

Stack Overflow用户
提问于 2017-03-22 06:31:54
回答 2查看 2.7K关注 0票数 0

我正在swift3中做一个项目,我有一个特定的UIViewController下载一个mp3到我的文件分析器,并且使用这个路径保存了,我想使用AVPlayer播放一个mp3。我的代码不起作用,我想我遗漏了什么。我怎样才能做到这一点?我的下载文件的代码如下所示

代码语言:javascript
复制
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下面。就目前而言,我已经硬编码了我保存的路径。密码如下。

代码语言:javascript
复制
    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)
      }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-22 09:00:17

您的问题是将URL设置为AVPlayer。实际上,在iOS中硬编码路径是行不通的,它可以在任何时候改变。

您需要以与destinationUrl相同的方式使用它:

代码语言:javascript
复制
    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!)
  

                         .
                         .
                         .
}

正常情况下它应该能工作。希望能帮上忙。

票数 3
EN

Stack Overflow用户

发布于 2017-03-22 06:54:01

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

代码语言:javascript
复制
 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方法中创建这些代码之后。您可以创建功能,为播放的声音类似;

代码语言:javascript
复制
func playSound() {

       if btnSound.isPlaying {
         btnSound.stop()
        }

        btnSound.play()

    }

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42944294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档