Skip to content

Instantly share code, notes, and snippets.

@xarbit
Forked from Cosmo/m3u.swift
Created March 30, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xarbit/8f584818d423929753251b9e8ee6e0e7 to your computer and use it in GitHub Desktop.
Save xarbit/8f584818d423929753251b9e8ee6e0e7 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment