Easy way to show SRT files on MPMoviePlayerController

Overview

Logo

issuesstarslicense

MPMoviePlayerController-Subtitles is a library to display subtitles on iOS. It's built as a Swift extension and it's very easy to integrate.

How To Get Started

Installation with CocoaPods

platform :ios, '8.0'
pod "MPMoviePlayerController-Subtitles"

Manually installation

Download (right-click) and add to your project.

Requirements

Version Language Minimum iOS Target
2.2.x Swift 3.x iOS 8
2.0.x Swift 2.x iOS 8
1.x Objective-C iOS 6

Usage with player

import MPMoviePlayerControllerSubtitles
// Video file
let videoFile = Bundle.main.path(forResource: "trailer_720p", ofType: "mov")

// Subtitle file
let subtitleFile = Bundle.main.path(forResource: "trailer_720p", ofType: "srt")
let subtitleURL = URL(fileURLWithPath: subtitleFile!)

// Movie player
let moviePlayerView = MPMoviePlayerViewController(contentURL: URL(fileURLWithPath: videoFile!))
presentMoviePlayerViewControllerAnimated(moviePlayerView)

// Add subtitles
moviePlayerView?.moviePlayer.addSubtitles().open(file: subtitleURL)
moviePlayerView?.moviePlayer.addSubtitles().open(file: subtitleURL, encoding: String.Encoding.utf8)

// Change text properties
moviePlayerView?.moviePlayer.subtitleLabel?.textColor = UIColor.red

// Play
moviePlayerView?.moviePlayer.play()

Screenshot

Screenshoot

Usage without player

From version 2.2 you can search text in the SubRip file or text without need play any file.

import MPMoviePlayerControllerSubtitles
// Subtitle file
let subtitleFile = Bundle.main.path(forResource: "trailer_720p", ofType: "srt")
let subtitleURL = URL(fileURLWithPath: subtitleFile!)

// Subtitle parser
let parser = Subtitles(file: subtitleURL, encoding: .utf8)

// Do something with result
let subtitles = parser.searchSubtitles(at: 2.0) // Search subtitle at 2.0 seconds

Contact

License

Licensed under Apache License v2.0.
Copyright 2017 Marc Hervera.

Comments
  • subtitleLabel blinking in 2 positions

    subtitleLabel blinking in 2 positions

    Hi, first i really thanks you for the library, it help me alot.

    I have using your library to reading subtitles in my video player, it's works fine, subtitle is showing when i watching video but it blinking in 2 positions. May you want to watching clip for more detail.

    https://www.dropbox.com/s/op2z83nyagfu2t0/Video%20Nov%2013%2C%2014%2002%2050.mov?dl=0

    I have running your example code and it has the same issue.

    opened by zikoops 12
  • Parser is failed to parse some files

    Parser is failed to parse some files

    Hi @mhergon ,

    I am facing some issue during parsing two files. https://dl.dropboxusercontent.com/u/32254461/Subtitles/English.srt [Successfully Parsing] https://dl.dropboxusercontent.com/u/32254461/Subtitles/Espanish.srt [Failed to Parse]

    Both files structure is same. You can view it by tapping on links.

    Code is breaking on these lines: NSString *textString; [scanner scanUpToString:@"\r\n\r\n" intoString:&textString]; textString = [textString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    "textString" is returning whole file data at once in case of some files. These are just sample files; Its also breaking for many English and Espanish files.

    Please look into the issue; If i am doing something wrong then please let me know.

    Thanks, Shafqat

    bug 
    opened by shafqat-muneer 11
  • Crashes on ios6 BAD_EXEC_

    Crashes on ios6 BAD_EXEC_

    Hi mhergon, i was so happy to implement your subtitle class into my app. but. it turns out it crashes on iOS 6.1 i get an bad exec when i start a movie, stop it, then play it again. its the same in your example. any idea?

    opened by Lorenzopet 10
  • Can it play online video?

    Can it play online video?

    I try use online video, the link is http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v My code as follows, let moviePlayerView = MPMoviePlayerViewController(contentURL: NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v"))

    It doesn't work. Can it support online video?

    opened by yuchin067 6
  • asynchronous between sound and video after while

    asynchronous between sound and video after while

    thx for this great lib but i think there is an issue, asynchronous between sound and video after while,what i mean that there is no match between sound and the scene after a while and this issue appears only if there is subtitle. thx in advance

    opened by hassan379 3
  • Support for objective c and to use .plist

    Support for objective c and to use .plist

    Hello mhergon,

    First of all great job you have done with this library

    Can you please provide update in Objective c and suggest me to a way for use .plist file instead of .srt file

    opened by vanditmehta 3
  • Crash

    Crash

    When video haven't display if you rotate screen your app will crash. Because this code

    • (void)updateLabelConstraints {

      // Default NSString *horizontal = @"H:|-(15)-[weakSubtitleLabel]-(15)-|"; NSString *vertical = @"V:[weakSubtitleLabel]-(15)-|";

      UIView __weak *weakSubtitleLabel = self.subtitleLabel; // Crash because weakSubtitleLable = nil NSDictionary *views = NSDictionaryOfVariableBindings(weakSubtitleLabel); NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontal options:0 metrics:nil views:views]; [self.subtitleLabel.superview addConstraints:constraints]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:vertical options:0 metrics:nil views:views]; [self.subtitleLabel.superview addConstraints:constraints];

      CGRect bounds = [self.subtitleLabel.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.subtitleLabel.bounds), CGFLOAT_MAX)
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName : self.subtitleLabel.font}
                                                            context:nil];
      self.heightConstraint.constant = bounds.size.height + 10.0;
      
      [self.subtitleLabel.superview layoutIfNeeded];
      

      }

    ---- So I change a little in this code

    • (void)updateLabelConstraints {

      // Default NSString *horizontal = @"H:|-(15)-[weakSubtitleLabel]-(15)-|"; NSString *vertical = @"V:[weakSubtitleLabel]-(15)-|";

      UIView *weak weakSubtitleLabel = self.subtitleLabel; __if (weakSubtitleLabel) { NSDictionary *views = NSDictionaryOfVariableBindings(weakSubtitleLabel); NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontal options:0 metrics:nil views:views]; [self.subtitleLabel.superview addConstraints:constraints]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:vertical options:0 metrics:nil views:views]; [self.subtitleLabel.superview addConstraints:constraints];

      CGRect bounds = [self.subtitleLabel.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.subtitleLabel.bounds), CGFLOAT_MAX)
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName : self.subtitleLabel.font}
                                                            context:nil];
      self.heightConstraint.constant = bounds.size.height + 10.0;
      
      [self.subtitleLabel.superview layoutIfNeeded];
      

      } }

    opened by nguyenhaidang 2
  • Trying to use this with AVPLayerViewController

    Trying to use this with AVPLayerViewController

    Hi I am trying to port this code to work with AVPlayerViewController with below minimal changes.

    // Video file let videoFile = NSBundle.mainBundle().pathForResource("trailer_720p", ofType: "mov")

        // Subtitle file
        let subtitleFile = NSBundle.mainBundle().pathForResource("trailer_720p", ofType: "srt")
        let subtitleURL = NSURL(fileURLWithPath: subtitleFile!)
        // Using AVPLAyerViewController
        let moviePlayerViewAV = AVPlayerViewController()
        moviePlayerViewAV.player = AVPlayer(URL: NSURL(fileURLWithPath: videoFile!))
        moviePlayerViewAV.addSubtitles().open(file: subtitleURL)
        moviePlayerViewAV.addSubtitles().open(file: subtitleURL, encoding: NSUTF8StringEncoding)
        // Change text properties
        moviePlayerViewAV.subtitleLabel?.textColor = UIColor.redColor()
        // Play
        moviePlayerViewAV.player!.play()
    

    And some changes in extension file. Below code is throwing exception "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format: Unable to interpret '|' character, because the related view doesn't have a superview H:|-(20)-[l]-(20)-| "

    subtitleContainer?.translatesAutoresizingMaskIntoConstraints = false subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(20)-[l]-(20)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!]) subtitleContainer?.addConstraints(constraints) constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[l]-(30)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!])

            subtitleContainer?.addConstraints(constraints)
            subtitleLabelHeightConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 30.0)
    

    Any help is appreciated.

    opened by dumne 2
  • Missing captions/texts in srt file causes crash

    Missing captions/texts in srt file causes crash

    Missing captions/texts in srt file causes crash

    Fixed this issue by add one validation in....

    pragma mark - Private methods

    • (void)parseString:(NSString *)string parsed:(void (^)(BOOL parsed, NSError *error))completion {

      // Create Scanner NSScanner *scanner = [NSScanner scannerWithString:string];

      // Subtitles parts self.subtitlesParts = [NSMutableDictionary dictionary];

      // Search for members while (!scanner.isAtEnd) {

      // Variables
      NSString *indexString;
      [scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet]
                              intoString:&indexString];
      
      NSString *startString;
      [scanner scanUpToString:@" --> " intoString:&startString];
      [scanner scanString:@"-->" intoString:NULL];
      
      NSString *endString;
      [scanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet]
                              intoString:&endString];
      
      
      
      NSString *textString;
      [scanner scanUpToString:@"\r\n\r\n" intoString:&textString];
      textString = [textString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
      
      // Regular expression to replace tags
      NSError *error = nil;
      NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:@"[<|\\{][^>|\\^}]*[>|\\}]"
                                                                              options:NSRegularExpressionCaseInsensitive
                                                                                error:&error];
      if (error) {
          completion(NO, error);
          return;
      }
      

      // if(textString.length>0){

      //Added by Vineeth

      if(!ISEMPTY(textString)){
      
      textString = [regExp stringByReplacingMatchesInString:textString
                                                    options:0
                                                      range:NSMakeRange(0, textString.length)
                                               withTemplate:@""];
      
      }else{
      
      
           textString =@"";
      
      }
      
      
      
      
      NSLog(@"textString is:%@",textString);
      
      
      // Temp object
      NSTimeInterval startInterval = [self timeFromString:startString];
      NSTimeInterval endInterval = [self timeFromString:endString];
      NSDictionary *tempInterval = @{
                                     kIndex : indexString,
                                     kStart : @(startInterval),
                                     kEnd : @(endInterval),
                                     kText : textString ? textString : @""
                                     };
      [self.subtitlesParts setObject:tempInterval
                              forKey:indexString];
      

      }

      NSLog(@"subtitlesParts is:%@",self.subtitlesParts);

      completion(YES, nil);

    }

    opened by vineethnk24 2
  • Carthage

    Carthage

    opened by TofPlay 1
  • Terminating app due to uncaught exception 'NSInternalInconsistencyException'

    Terminating app due to uncaught exception 'NSInternalInconsistencyException'

    Hello, I got this issue when reading video and its sub: "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSDictionaryOfVariableBindings failed because either one of the values is nil, or there's something wrong with the way the macro is being invoked. Cannot assign value nil for key "weakSubtitleLabel". Keys:( weakSubtitleLabel )'" I created this subtitle by following: [self.item.srtSubtitle writeToFile:srtSubPath atomically:YES encoding:NSUTF8StringEncoding error:&error]; The video and its sub can be downloaded here: https://www.dropbox.com/sh/zgmxujxerydhz9q/AAAlQp7sAMW2_ISJwZ9NO47Xa?dl=0# I've been trying to create the sub with different encoding like: NSUTF8StringEncoding, NSISOLatin1StringEncoding but no luck. Please help me. Thank you.

    opened by tuanbs 1
Releases(v2.2.2)
Owner
Marc Hervera
 iOS, macOS, tvOS, watchOS, Vapor developer, instructor and more... 
Marc Hervera
A lightweight app to play videos from the Files app in a better (dark) interface which avoids losing your playback position.

Playerly Playerly is a very lightweight Swift app that allows you to select a file (video or movie) from the built in Document Browser, and play it in

Julian Schiavo 28 Dec 3, 2022
A Swift library to upload video files to api.video platform.

api.video IOS video uploader api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and manag

api.video 7 Dec 9, 2022
This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable coding methodologies!

YouTubeClone This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable co

Vamshi Krishna 169 Dec 10, 2022
▶️ video player in Swift, simple way to play and stream media on iOS/tvOS

Player Player is a simple iOS video player library written in Swift. Looking for an obj-c video player? Check out PBJVideoPlayer (obj-c). Looking for

patrick piemonte 2k Jan 2, 2023
The best way to watch Put.io on iPhone and iPad

The best way to watch Put.io on iPhone and iPad

Fetch 89 Oct 27, 2022
This Google Cast demo app shows how to cast videos from an iOS device in a way that is fully compliant with the Cast Design Checklist.

CastVideos-ios (reference iOS sender app) This Google Cast demo app shows how to cast videos from an iOS device in a way that is fully compliant with

Google Cast 168 Jan 6, 2023
A video composition framework build on top of AVFoundation. It's simple to use and easy to extend.

A high-level video composition framework build on top of AVFoundation. It's simple to use and easy to extend. Use it and make life easier if you are implementing video composition feature.

VideoFlint 1.4k Dec 25, 2022
A high-performance, flexible, and easy-to-use Video compressor library written by Swift.

FYVideoCompressor A high-performance, flexible and easy to use Video compressor library written by Swift. Using hardware-accelerator APIs in AVFoundat

null 30 Dec 30, 2022
YHPlayer - An easy-to-use video player based on swift language

YHPlayer An easy-to-use video player based on swift language Features Plays loca

null 9 Dec 1, 2022
A SwiftUI framework which makes it easy to integrate Video Call and Chat within a few lines of code.

Welcome to iStream! This SwiftUI Framework allows you to add Video Call and Chat to your project within a few lines of code. To use this Framework, yo

null 2 Aug 19, 2022
Easy way to show SRT files on AVPlayerViewController

    AVPlayerViewController-Subtitles is a library to display subtitles on iOS. It's built as a Swift extension and it's very easy to integrate. How To

Marc Hervera 216 Dec 23, 2022
Package for creating, modifying, and managing subtitle files, such as SubRip (.srt).

SubtitleKit Package for creating, modifying, and managing subtitle files, such as SubRip (.srt). Supported formats Format File extension Is supported

GGorAA 2 Oct 28, 2022
Easy and beautiful way for a user to pick content, files or images. Written in Objective C

##JVTImageFilePicker Description ImageFilesPicker Is a butifuly designed UICompenent for uploading content Preview from recent camera roll Live Camera

Matan Abravanel 60 Jun 19, 2022
Localization/I18n: Incrementally update/translate your Strings files from .swift, .h, .m(m), .storyboard or .xib files.

Installation • Configuration • Usage • Build Script • Donation • Migration Guides • Issues • Contributing • License BartyCrouch BartyCrouch incrementa

Flinesoft 1.3k Jan 1, 2023
Mahmoud-Abdelwahab 5 Nov 23, 2022
Show the confetti only when the user is having fun, and if not having fun, don't show it.

SPConfetti - A simple solution to show the confetti to the user. Smoothly starts and stops. Allow set multiply diffrent particles at once. You can chang

Ivan Vorobei 225 Dec 30, 2022
A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using external references approach.

multipleP21ReadsSample A Swift sample code to reads ISO 10303-21 exchange structures (STEP P21 files for AP242) split into multiple files using extern

Tsutomu Yoshida 1 Nov 23, 2021
Classes-and-structures-in-swift - This source files show what is the difference between class and structure

This source files show what is the difference between class and structure You ca

null 0 Jan 4, 2022
BeatboxiOS - A sample implementation for merging multiple video files and/or image files using AVFoundation

MergeVideos This is a sample implementation for merging multiple video files and

null 3 Oct 24, 2022
Shawn Frank 2 Aug 31, 2022