Downloaded an Audio file into File Manager need to play it from local path

*爱你&永不变心* 提交于 2019-12-11 18:12:26

问题


I am working in an audio player application, and also I am having a offline download option, when the user click the download button it should start download and save it into local. I have saved it using file manager URLSession.

I have tried of taking and separating the destination url. I am using a jukebox third party for playing the song. the sample file location is

file:///var/mobile/Containers/Data/Application/BBB9AF1C-D87C-4C40-9F29-AD89062A20E2/Documents/05-KARMA-YOGA.mp3

if let audioUrl = URL(string: audioTobedownloaded) {
            // then lets create your document folder url
            let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            // lets create your destination file url
            let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
            print(destinationUrl)

the actual thing is how should I play the audio which I have downloaded in file manager.


回答1:


func findFilesWith(extensionType: String) -> [URL]{
        var matches = [URL]()
        let fileManager = FileManager.default

        let files = fileManager.enumerator(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        // *** this section here adds all files with the chosen extension to an array ***
        for item in files!
        {
            let fileURL = item as! URL

            if (fileURL.pathExtension == extensionType)
            {
                matches.append(fileURL)
            }
        }
        return matches
    }

You can use this method to get all kinds of file with respective to the extension type.

In your case use mp3 as extension type

Try the below method to play audio from the fetched url

func play(url:URL) {
        print("playing \(url)")

        do {
            let player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.volume = 1.0
            player.play()
        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("AVAudioPlayer init failed")
        }

    }


来源:https://stackoverflow.com/questions/54544067/downloaded-an-audio-file-into-file-manager-need-to-play-it-from-local-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!