Skip to content

Instantly share code, notes, and snippets.

@Cosmo
Last active August 21, 2023 09:59
Show Gist options
  • Save Cosmo/19bb4a65a49873217e42 to your computer and use it in GitHub Desktop.
Save Cosmo/19bb4a65a49873217e42 to your computer and use it in GitHub Desktop.
Swift M3U Parser
struct MediaItem {
var duration: Int?
var title: String?
var urlString: String?
static func parseM3U(contentsOfFile: String) -> [MediaItem]? {
var mediaItems = [MediaItem]()
contentsOfFile.enumerateLines({ line, stop in
if line.hasPrefix("#EXTINF:") {
let infoLine = line.stringByReplacingOccurrencesOfString("#EXTINF:", withString: "")
let infos = Array(infoLine.componentsSeparatedByString(","))
if let durationString = infos.first, duration = Int(durationString) {
let mediaItem = MediaItem(duration: duration, title: infos.last, urlString: nil)
mediaItems.append(mediaItem)
}
} else {
if mediaItems.count > 0 {
var item = mediaItems.last
item?.urlString = line
}
}
})
return mediaItems
}
}
if let
path = NSBundle.mainBundle().pathForResource("playlist", ofType: "m3u"),
contentsOfFile = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
MediaItem.parseM3U(contentsOfFile)
}
@MaatheusGois
Copy link

Swift 5.6

struct MediaItem {
    var duration: Int?
    var title: String?
    var urlString: String?

    static func parseM3U(contentsOfFile: String) -> [MediaItem]? {
        var mediaItems = [MediaItem]()
        contentsOfFile.enumerateLines(invoking: { line, stop in
            if line.hasPrefix("#EXTINF:") {
                let infoLine = line.replacingOccurrences(of: "#EXTINF:", with: "")
                let infos = Array(infoLine.split(separator: ","))

                let durationString = String(infos.first ?? "")
                if let duration = Int(durationString) {

                    let mediaItem = MediaItem(
                        duration: duration,
                        title: String(infos.last ?? ""),
                        urlString: nil
                    )
                    mediaItems.append(mediaItem)
                }
            } else {
                if mediaItems.count > 0 {
                    var item = mediaItems.last
                    item?.urlString = line
                }
            }
        })
        return mediaItems
    }

    static func getDefault() {

        if
            let path = Bundle.main.path(forResource: "playlist", ofType: "m3u"),
            let contentsOfFile = try? String(contentsOfFile: path, encoding: String.Encoding(rawValue: NSUTF8StringEncoding)) {
            dump(MediaItem.parseM3U(contentsOfFile: contentsOfFile))
        }

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment