Skip to content

Instantly share code, notes, and snippets.

@shayanbo
Last active September 22, 2016 08:04
Show Gist options
  • Save shayanbo/5267025e388184725aed240da89b1ef1 to your computer and use it in GitHub Desktop.
Save shayanbo/5267025e388184725aed240da89b1ef1 to your computer and use it in GitHub Desktop.
Convert srt(subtitle) to common article
//
// main.swift
// SRTConverter
//
// Created by shayanbo on 22/09/2016.
// Copyright © 2016 shayanbo. All rights reserved.
// using swift3.0
import Foundation
enum SRTDataType: String {
case WEBVTT
case MediaPoint = "-->"
case EmptyLine = ""
case Timestamp = "TIMESTAMP"
case Subtitle
static func dataType(line: String) -> SRTDataType {
if line == SRTDataType.EmptyLine.rawValue {
return .EmptyLine
} else if line.contains(SRTDataType.MediaPoint.rawValue) {
return .MediaPoint
} else if line.contains(SRTDataType.Timestamp.rawValue) {
return .Timestamp
} else if line.contains(SRTDataType.WEBVTT.rawValue) {
return .WEBVTT
} else {
return .Subtitle
}
}
}
func convert(srt: String) -> String {
var newContent = ""
let lines = srt.components(separatedBy: CharacterSet.newlines)
for line in lines {
if SRTDataType.dataType(line: line) == .Subtitle {
newContent += line + "\n"
}
}
return newContent
}
if let urlString = ProcessInfo.processInfo.arguments.dropFirst().first {
if let url = URL(string: urlString) {
do {
let srtContent = try String(contentsOf: url, encoding:.utf8)
let convertedContent = convert(srt: srtContent)
let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let targetUrl = URL(fileURLWithPath: url.deletingPathExtension().lastPathComponent, relativeTo: currentDirectoryURL)
try convertedContent.write(to: targetUrl, atomically: true, encoding: .utf8)
} catch {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment