6

I am trying to concatenate .ts files present in a .m3u8 playlist in python,

Is there any way of doing it ??? If yes please do explain how

Thanks in advance

torment32
  • 85
  • 1
  • 9

1 Answers1

12

This should work, I only added two comments to this short script cause I guess it's pretty much self-explanatory.

import shutil

# Parse playlist for filenames with ending .ts and put them into the list ts_filenames
with open('playlist.m3u8', 'r') as playlist:
    ts_filenames = [line.rstrip() for line in playlist
                    if line.rstrip().endswith('.ts')]

# open one ts_file from the list after another and append them to merged.ts
with open('merged.ts', 'wb') as merged:
    for ts_file in ts_filenames:
        with open(ts_file, 'rb') as mergefile:
            shutil.copyfileobj(mergefile, merged)
barrios
  • 1,104
  • 1
  • 12
  • 21
  • Hey,Thanks for the reply.....the m3u8 file which I am using is online as a link....which won't work with this solution....:/ – torment32 Mar 14 '14 at 11:56
  • well .....I was able to solve that issue......but could you tell me.....where will the merged.ts be saved ?? – torment32 Mar 14 '14 at 12:00
  • It will be saved to the dir where you started the script. But you are free to specify a path, just be aware to use a raw string on windows so you don't have to escape the backslashes. e.g. open(r'C:\path\to\merged.ts', 'wb'). BTW Please be so kind to vote this answer up if it was helpful to you. – barrios Mar 14 '14 at 12:56
  • I can't vote up....not enough reputation for that....and thanks for the answer :) – torment32 Mar 18 '14 at 05:58
  • I don't think it is sufficient. Concatenating the files from the command line does not work. I think you have to extract the video and audio streams and re-encapsulate them – robertspierre Nov 19 '18 at 23:35
  • robertspierre: you're wrong, that anwer works perfectly and its shortest I've found – Tom St Dec 31 '21 at 20:21