我很新
所以這個 getLength 函式將在 python 2.7 中運行良好,但我無法讓它在 3.10 中運行。想知道是否有人可以建議可能需要更改的內容,因為我不知所措。當我嘗試列印退貨時,那里什么都沒有。我 95% 確定問題出在 result = subprocess.Popen() 行,但為了完整起見,我包含了整個函式
#function... 回傳視頻檔案的持續時間 HH:MM:SS
def getLength(filename):
#uses ffprobe to get info about the video file
result = subprocess.Popen(["ffprobe", filename],
stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#finds the info that has the word "Duration"
y = [x for x in result.stdout.readlines() if "Duration: " in x]
#get the location of the "Duration: " phrase
loc = y[0].find("Duration: ")
#assuming we find the location of that phrase..
if loc != -1:
#cut out everything before and everything more than 10 characters later
print ( y[0][loc 10:loc 18] )
return y[0][loc 10:loc 18]
else:
#if we don't find anything then set it to be 2 seconds of nothing...
print ( y[0][loc 10:loc 18] )
return '00:00:02'
uj5u.com熱心網友回復:
在 Python 3 中,字串是Unicode 格式,stdout輸出是位元組陣列。
我們可以使用以下方法將位元組陣列轉換為字串x.decode("utf-8"):
決議串列可能如下所示:
y = [x.decode("utf-8") for x in result.stdout.readlines() if "Duration: " in x.decode("utf-8")]
完整的代碼示例(使用stderr代替stdout):
import subprocess
def get_length(filename):
# Uses FFprobe to get info about the video file
result = subprocess.Popen(["ffprobe", filename], stderr=subprocess.PIPE)
# Finds the info that has the word "Duration"
# Convert bytes array to strings using decode("utf-8")
y = [x.decode("utf-8") for x in result.stderr.readlines() if "Duration: " in x.decode("utf-8")]
# Get the location of the "Duration: " phrase
loc = y[0].find("Duration: ")
# Assuming we find the location of that phrase..
if loc != -1:
# Cut out everything before and everything more than 10 characters later
print(y[0][loc 10:loc 18])
return y[0][loc 10:loc 18]
else:
# If we don't find anything then set it to be 2 seconds of nothing...
print(y[0][loc 10:loc 18])
return '00:00:02'
res = get_length('BBB.ogv')
print(res)
為了獲取 OVG(或 MP4)檔案的視頻時長,我們可以選擇 JSON 格式:
import subprocess as sp
import json
# https://superuser.com/questions/650291/how-to-get-video-duration-in-seconds
data = sp.run(["ffprobe", '-v', 'error', '-select_streams', 'v', '-of', 'default=noprint_wrappers=1:nokey=1', '-show_entries', 'stream=duration', '-of', 'json', 'BBB.ogv'], stdout=sp.PIPE).stdout
dict = json.loads(data)
print(dict['streams'][0]['duration'])
uj5u.com熱心網友回復:
我很確定python3中的輸出是位元組流而不是str。
嘗試這個:
import subprocess
media = "/home/rolf/BBB.ogv"
try:
comm = subprocess.Popen(['ffprobe', '-hide_banner', '-show_entries', 'format=size, duration',\
'-i', media], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
except Exception as e:
pass
try:
with comm.stdout:
for i in iter(comm.stdout.readline, b''):
if i != '':
print(i)
else:
break
except Exception as e:
print("Error: ", str(e))
輸出:
python probe.py
Input #0, ogg, from '/home/rolf/BBB.ogv':
Duration: 00:01:00.14, start: 0.000000, bitrate: 264 kb/s
Stream #0:0(eng): Video: theora, yuv420p, 640x360 [SAR 1:1 DAR 16:9], 24 fps, 24.04 tbr, 24.04 tbn
Metadata:
creation_time : 2011-03-16 10:41:52
handler_name : Apple Video Media Handler
encoder : Lavc56.60.100 libtheora
major_brand : mp42
minor_version : 1
compatible_brands: mp42avc1
Stream #0:1(eng): Audio: vorbis, 44100 Hz, mono, fltp, 80 kb/s
Metadata:
creation_time : 2011-03-16 10:41:53
handler_name : Apple Sound Media Handler
encoder : Lavc56.60.100 libvorbis
major_brand : mp42
minor_version : 1
compatible_brands: mp42avc1
[FORMAT]
duration=60.139683
size=1992112
[/FORMAT]
uj5u.com熱心網友回復:
如果您對以秒為單位的持續時間(不在HH:MM:SS符號中)感到滿意,我更喜歡使用該-of json選項,以便我可以使用json包來決議 ffprobe 輸出:
import subprocess as sp
import json
from pprint import pprint
out = sp.run(['ffprobe','-hide_banner','-of','json',
'-show_entries','format:stream', f'"{filename}"'],
stdout=sp.PIPE, universal_newlines=True)
results = json.loads(out.stdout)
pprint(results) # to see the full details
format_duration = float(results['formats']['duration']) # in seconds
stream_durations = [float(st['duration']) for st in results['streams']] # in seconds
注意:您必須指定-show_entries選項,否則它將回傳空 JSON
只需插入我的庫 ( pip install fmpegio-core),您可以交替運行:
import ffmpegio
file_duration = ffmpegio.probe.format_basic(filename)['duration']
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/428045.html
標籤:python-3.x python-2.7 ffmpeg ffprobe python-3.10
下一篇:模塊已安裝但未匯入
