Map mp3 s in Documents directory and convert to AVPlayerItems

Map mp3 s in Documents directory and convert to AVPlayerItems



I am using this method to convert an mp3 in my main bundle path to an avplayer item:


let path = Bundle.main.path(forResource: "Baroon", ofType: "mp3")
let url = URL(fileURLWithPath: path!)
let asset = AVAsset(url: url)
let item = AVPlayerItem(asset: asset)



How can I convert every mp3 that exist in the Documents directory automatically?




2 Answers
2



You can use FileManager's contentsOfDirectory(of: URL) method to get all files in your documents directory and map the ones that contains the mp3 pathExtension:


contentsOfDirectory(of: URL)


let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do
let playesItems = try FileManager.default.contentsOfDirectory(at: documents, includingPropertiesForKeys: nil).compactMap
$0.pathExtension == "mp3" ? $0.asset.playerItem : nil

for item in playesItems
print(item.asset.duration)

catch print(error)



Don't forget to add those helpers to your project:


import UIKit
import AVKit

extension URL
var asset: AVAsset
return AVAsset(url: self)


extension AVAsset
var playerItem: AVPlayerItem
return AVPlayerItem(asset: self)




The Bundle class has a method urls(forResourcesWithExtension:subdirectory:) That will return all the files in the bundle (or in a subdirectory of that bundle) with a given file extension. Use that to search for all files with the extension "mp3" and then iterate through them and create AVPlayerItems out of each one.


Bundle


urls(forResourcesWithExtension:subdirectory:)


AVPlayerItem





Appreciate for your answer❤️
– namaama
Sep 3 at 1:32



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)