Skip to main content
 首页 » 编程设计

python之如何仅从视频文件中获取第一个隐藏式字幕

2025年05月04日9kerrycode

我需要在我的硬盘上找到一些视频文件的开始日期。修改日期或文件名等对我没有帮助 - 真正的开始时间在隐藏式字幕中。

使用 CCExtractor还有一些Python Popen ...

import subprocess 
process = subprocess.Popen(['ccextractorwin.exe', 'mycaptions.srt', '-quiet', 
        'myvideo.mpg'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
out, err = process.communicate() 

这会生成一个隐藏式字幕 .srt 文件,我想要的肯定在那里:

1 
00:00:00,000 --> 00:00:06,772 
4756.9585N, 12905.8976W, 1885    
2013-06-20 16:50:29, Hdg: 54                 
 
2 
00:00:06,774 --> 00:00:07,373 
2013-06-20 16:50:29, Hdg: 54                
4756.9585N, 12905.8976W, 1883    
 
... 

但问题是这些视频文件有数百 GB,而 CCExtractor 会生成整个字幕文件。我只需要开始时间,它在第一个条目中。

CCExtractor 或其他(免费)工具是否有一个模糊的未记录的选项可以让我只获得第一个条目?

我能想到的唯一替代方法是启动 CCExtractor,生成一个线程来读取正在生成的字幕文件,然后终止 CCExtractor 进程和读取线程。还不错,但我想先看看是否有更好的出路。

请您参考如下方法:

不是使用 process.communicate(),它会阻塞直到从应用程序读取所有数据,而是逐行读取结果作为流。然后,您可以在阅读了尽可能多的内容后终止底层进程。您还需要使用标志 -stdout 将输出从 ccextractorwin.exe 重定向到 STDOUT。

import subprocess 
process = subprocess.Popen( 
    ['ccextractorwin.exe', '-stdout', '-quiet', 'myvideo.mpg'], 
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT 
) 
all_output = [] 
while True: 
    out_line = process.stdout.readline() 
    all_output.append(out_line)  # Add this line to the list of lines to keep 
    if out_line == u'\n':  # We've hit an empty line, or whatever else you deem like a good stopping point 
        break  # the while loop 
 
# Now, kill the process dead in its tracks. 
# This probably isn't great for open file handles, but whatever 
process.kill() 

这会将 SIGKILL 发送到应用程序,这可能(当然)在 Windows 上与在 Linux 或 OSX 上的工作方式不同。如果有问题,请在此处查看有关终止它的替代解决方案:In Python 2.5, how do I kill a subprocess?

希望对您有所帮助。