将音频文件下载到“文件管理器”中需要从本地路径播放 [英] Downloaded an Audio file into File Manager need to play it from local path

查看:164
本文介绍了将音频文件下载到“文件管理器”中需要从本地路径播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用音频播放器应用程序,并且还具有脱机下载选项,当用户单击下载按钮时,它应该开始下载并将其保存到本地。我已经使用文件管理器URLSession保存了它。

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

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.

推荐答案

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.

在您的情况下,请使用mp3作为扩展名

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

    }

这篇关于将音频文件下载到“文件管理器”中需要从本地路径播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆