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 AVPlayerItem
s out of each one.
Bundle
urls(forResourcesWithExtension:subdirectory:)
AVPlayerItem
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.
Appreciate for your answer❤️
– namaama
Sep 3 at 1:32