ffmpeg 출력에서 지속 시간을 추출하는 방법은 무엇입니까?
미디어 파일에 대한 많은 정보를 얻으려면
ffmpeg -i <filename>
많은 줄을 출력합니다. 특히 하나는
Duration: 00:08:07.98, start: 0.000000, bitrate: 2080 kb/s
출력 00:08:07.98만하고 싶기 때문에
ffmpeg -i file.mp4 | grep Duration| sed 's/Duration: \(.*\), start/\1/g'
그러나 길이뿐만 아니라 모든 것을 인쇄합니다.
심지어 ffmpeg -i file.mp4 | grep Duration모든 것을 출력합니다.
기간 길이를 어떻게 얻습니까?
는 FFmpeg는 해당 정보를 기록하고 stderr,하지 stdout. 이 시도:
ffmpeg -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start/\1/g'
의 리디렉션 stderr을 확인하십시오 stdout.2>&1
편집하다:
귀하의 sed진술도 작동하지 않습니다. 이 시도:
ffmpeg -i file.mp4 2>&1 | grep Duration | awk '{print $2}' | tr -d ,
다음을 사용할 수 있습니다 ffprobe.
ffprobe -i <file> -show_entries format=duration -v quiet -of csv="p=0"
다음과 같이 초 단위로 기간을 출력합니다.
154.12
-sexagesimal옵션을 추가하면 시간이 시간 : 분 : 초 . 마이크로 초로 출력됩니다 .
00:02:34.12
내 경험으로 볼 때 많은 도구가 일종의 테이블 / 순서화 된 구조로 원하는 데이터를 제공하고 해당 데이터의 특정 부분을 수집하기위한 매개 변수도 제공합니다. 이것은 예를 들어 smartctl, nvidia-smi 및 ffmpeg / ffprobe에도 적용됩니다. 간단히 말해서-종종 그러한 작업을 위해 데이터를 파이프하거나 하위 쉘을 열 필요가 없습니다.
결과적으로 작업에 적합한 도구를 사용합니다.이 경우 ffprobe는 원시 기간 값을 초 단위로 반환하고 나중에 원하는 시간 형식을 직접 만들 수 있습니다.
$ ffmpeg --version
ffmpeg version 2.2.3 ...
명령은 사용중인 버전에 따라 다를 수 있습니다.
#!/usr/bin/env bash
input_file="/path/to/media/file"
# Get raw duration value
ffprobe -v quiet -print_format compact=print_section=0:nokey=1:escape=csv -show_entries format=duration "$input_file"
설명:
"-v quiet": 원하는 원시 데이터 값 외에는 출력하지 않습니다.
"-print_format": 특정 형식을 사용하여 데이터를 인쇄합니다.
"compact =": 압축 출력 형식 사용
"print_section = 0": 섹션 이름을 인쇄하지 않습니다.
": nokey = 1": 키 : 값 쌍의 키를 인쇄하지 않습니다.
": escape = csv": 값을 이스케이프
"-show_entries format = duration": format이라는 섹션 내에서 duration이라는 필드의 항목을 가져옵니다.
참조 : ffprobe 매뉴얼 페이지
하나의 요청 매개 변수의 경우 mediainfo 및 해당 출력 형식을 다음과 같이 사용하는 것이 더 간단합니다 (기간 동안, 밀리 초 단위로 응답).
amber ~ > mediainfo --Output="General;%Duration%" ~/work/files/testfiles/+h263_aac.avi
24840
json 형식을 사용하는 것이 좋습니다. 파싱이 더 쉽습니다.
ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner
{
"streams": [
{
"index": 0,
"codec_name": "aac",
"codec_long_name": "AAC (Advanced Audio Coding)",
"profile": "HE-AACv2",
"codec_type": "audio",
"codec_time_base": "1/44100",
"codec_tag_string": "[0][0][0][0]",
"codec_tag": "0x0000",
"sample_fmt": "fltp",
"sample_rate": "44100",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/28224000",
"duration_ts": 305349201,
"duration": "10.818778",
"bit_rate": "27734",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0
}
}
],
"format": {
"filename": "your-input-file.mp4",
"nb_streams": 1,
"nb_programs": 0,
"format_name": "aac",
"format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
"duration": "10.818778",
"size": "37506",
"bit_rate": "27734",
"probe_score": 51
}
}
형식 섹션에서 기간 정보를 찾을 수 있으며 비디오 및 오디오 모두에서 작동합니다.
ffmpeg -i abc.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed s/,//
출력을 제공
HH : MM : SS.milisecs
최선의 해결책 : 수출을 줄이면 00 : 05 : 03.22
ffmpeg -i input 2>&1 | grep Duration | cut -c 13-23
Windows에서 추가 소프트웨어없이 동일한 계산을 수행하려는 사용자를 위해 다음은 명령 줄 스크립트 용 스크립트입니다.
set input=video.ts
ffmpeg -i "%input%" 2> output.tmp
rem search " Duration: HH:MM:SS.mm, start: NNNN.NNNN, bitrate: xxxx kb/s"
for /F "tokens=1,2,3,4,5,6 delims=:., " %%i in (output.tmp) do (
if "%%i"=="Duration" call :calcLength %%j %%k %%l %%m
)
goto :EOF
:calcLength
set /A s=%3
set /A s=s+%2*60
set /A s=s+%1*60*60
set /A VIDEO_LENGTH_S = s
set /A VIDEO_LENGTH_MS = s*1000 + %4
echo Video duration %1:%2:%3.%4 = %VIDEO_LENGTH_MS%ms = %VIDEO_LENGTH_S%s
Same answer posted here: How to crop last N seconds from a TS video
If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:
import subprocess
import json
input_file = "< path to your input file here >"
metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))
metadata = json.loads(metadata)
print(f"Length of file is: {float(length["format"]["duration"])}")
print(metadata)
Output:
Length of file is: 7579.977143
{
"streams": [
{
"index": 0,
"codec_name": "mp3",
"codec_long_name": "MP3 (MPEG audio layer 3)",
"codec_type": "audio",
"codec_time_base": "1/44100",
"codec_tag_string": "[0][0][0][0]",
"codec_tag": "0x0000",
"sample_fmt": "fltp",
"sample_rate": "44100",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/14112000",
"start_pts": 353600,
"start_time": "0.025057",
"duration_ts": 106968637440,
"duration": "7579.977143",
"bit_rate": "320000",
...
...
I would just do this in C++ with a text file and extract the tokens. Why? I am not a linux terminal expert like the others.
To set it up I would do this in Linux..
ffmpeg -i 2>&1 | grep "" > mytext.txt
and then run some C++ app to get the data needed. Maybe extract all the important values and reformat it for further processing by using tokens. I will just have to work on my own solution and people will just make fun of me because I am a linux newbie and I do not like scripting too much.
Argh. Forget that. It looks like I have to get the cobwebs out of my C and C++ programming and use that instead. I do not know all the shell tricks to get it to work. This is how far I got.
ffmpeg -i myfile 2>&1 | grep "" > textdump.txt
and then I would probably extract the duration with a C++ app instead by extracting tokens.
I am not posting the solution because I am not a nice person right now
Update - I have my approach to getting that duration time stamp
Step 1 - Get the media information on to a text file
`ffprobe -i myfile 2>&1 | grep "" > textdump.txt`
OR
`ffprobe -i myfile 2>&1 | awk '{ print }' > textdump.txt`
Step 2 - Home in on the information needed and extract it
cat textdump.txt | grep "Duration" | awk '{ print $2 }' | ./a.out
Notice the a.out. That is my C code to chop off the resulting comma because the output is something like 00:00:01.33,
Here is the C code that takes stdin and outputs the correct information needed. I had to take the greater and less than signs out for viewing.
#include stdio.h #include string.h void main() { //by Admiral Smith Nov 3. 2016 char time[80]; int len; char *correct; scanf("%s", &time); correct = (char *)malloc(strlen(time)); if (!correct) { printf("\nmemory error"); return; } memcpy(correct,&time,strlen(time)-1); correct[strlen(time)]='/0'; printf("%s", correct); free(correct); }
Now the output formats correctly like 00:00:01.33
You could try this:
/*
* Determine video duration with ffmpeg
* ffmpeg should be installed on your server.
*/
function mbmGetFLVDuration($file){
//$time = 00:00:00.000 format
$time = exec("ffmpeg -i ".$file." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
$duration = explode(":",$time);
$duration_in_seconds = $duration[0]*3600 + $duration[1]*60+ round($duration[2]);
return $duration_in_seconds;
}
$duration = mbmGetFLVDuration('/home/username/webdir/video/file.mov');
echo $duration;
ffmpeg has been substituted by avconv: just substitute avconb to Louis Marascio's answer.
avconv -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start.*/\1/g'
Note: the aditional .* after start to get the time alone !!
참고URL : https://stackoverflow.com/questions/6239350/how-to-extract-duration-time-from-ffmpeg-output
'Program Club' 카테고리의 다른 글
| 이전 node.js 버전을 제거하거나 업그레이드하려면 어떻게해야합니까? (0) | 2020.11.22 |
|---|---|
| JQuery 배열에서 속성으로 객체를 찾는 방법 (0) | 2020.11.22 |
| Java에서 ArrayList를 Array로 변환 (0) | 2020.11.22 |
| Android Google Maps v2 : 여러 줄 스 니펫으로 마커를 추가하는 방법은 무엇입니까? (0) | 2020.11.22 |
| Android Studio가 '파일이 잠겨 있음'오류를 표시하여 열지 못했습니다. (0) | 2020.11.22 |