Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제

예전에 FFmpeg.AutoGen 패키지를 알아봤었는데요, 여전히 그게 선택지의 하나이긴 해도 이번에는 다른 걸로, 제목에 소개했듯이 FFMpegCore 패키지로 실습해 보겠습니다. ^^

FFMpegCore
; https://www.nuget.org/packages/FFMpegCore

rosenbjerg/FFMpegCore
; https://github.com/rosenbjerg/FFMpegCore

A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications. Supports both synchronous and asynchronous calls


repo의 설명에서는 "FFMpeg/FFProbe wrapper"라고 하는데요, 보다 더 엄밀히 말하면 "FFMpeg.exe/FFProbe.exe wrapper"가 맞습니다. ^^; 즉, ffmpeg.exe/ffproble.exe 파일을 실행한 후 그 출력 결과를 파싱한 결과를 이용하는 방식입니다. 환경 구성은 패키지를 설치 후,

Install-Package FFMpegCore

빌드하면 143KB 크기의 FFMpegCore.dll 파일이 함께 출력되는데요, 이후 실행 시 ffmpeg.exe/ffprobe.exe를 찾을 수 있도록 PATH 환경 변수에 있거나, 처음부터 EXE 파일이 있는 폴더에 그 파일들이 있으면 됩니다.




실습을 위해, Youtube에서 동영상을 하나 다운로드한 후, 오디오만을 분리해 mp3 파일로 저장하는 것이 이렇게나 간단합니다. ^^

string inputPath = @"c:\fftemp\test.mp4";
FFMpeg.ExtractAudio(inputPath, "test.mp3"); // mp3 확장자 필수!

// 오디오 파일의 확장자를 mp3가 아닌 다른 걸로 지정하면 예외가 발생합니다. 
/*
Unhandled exception. FFMpegCore.Exceptions.FFMpegException: Invalid output file. File extension should be '.mp3' required.
*/

벌써 제목에 소개한 기능의 설명이 끝났군요. ^^ 그래도 이대로는 아쉬우니 좀 더 살펴보겠습니다. 우선, Windows의 File Explorer에서 동영상 파일의 속성을 "Details" 패널을 통해 살펴봤더니 이런 정보가 나옵니다.

Length: 00:08:02
Frame width: 1920
Frame height: 1080
Frame rate: 29.97 frames/second
Data rate: 2356kbps
Total bitrate: 2484kbps

위의 정보를 FFMpegCore로 맞춰보면 "Total bitrate"를 제외하고는 대충 다음과 같이 구할 수 있습니다.

string inputPath = @"c:\fftemp\test.mp4";

var mediaInfo = await FFProbe.AnalyseAsync(inputPath);
Console.WriteLine($"Length: {mediaInfo.Duration}");

var videoStream = mediaInfo.PrimaryVideoStream;
Console.WriteLine($"Frame width: {videoStream?.Width}");
Console.WriteLine($"Frame height: {videoStream?.Height}");

Console.WriteLine($"Frame rate: {videoStream?.FrameRate:00.00} frames/second");
Console.WriteLine($"Data rate: {videoStream?.BitRate / 1000}kbps");

"Total bitrate"의 경우 이거저거 구해 조합해 보면 Video와 Audio의 Bitrate를 더한 값인 듯합니다. (실제로 그 값인지는 모르겠습니다. ^^;)

var videoStream = mediaInfo.PrimaryVideoStream;
var audioStream = mediaInfo.PrimaryAudioStream;

Console.WriteLine($"Total bitrate: {(videoStream?.BitRate + audioStream?.BitRate) / 1000}kbps");

그나저나, 저처럼 관련 업계의 지식이 빈약한 사람은 저 용어들 자체가 낯설기만 한데요, 위의 경우 Bit Rate가 왜 Data rate 값으로 평가되는지 좀 헷갈리는데 아래의 글에서 이에 대해 자세하게 설명하고 있습니다. ^^

Bit Rate vs Data Rate
; https://wolfcrow.com/bit-rate-vs-data-rate/

정리해 보면, 프레임의 인코딩 결과가 CBR(Constant Bit Rate)로 나온다면 Bit rate가 곧 Data rate에 해당할 수 있습니다. 하지만, VBR(Variable Bit Rat)로 프레임이 압축된다면 Bit rate가 프레임 별로 달라지므로 Data rate를 알 수 없고 그 순간까지의 "Average Bit Rate (평균 비트 전송률)"만을 알 수 있습니다. 그러다, 재생이 완료된 시점에는 전체 데이터를 시간으로 나눠 Data rate를 구할 수 있다고 합니다.

가령, VBR로 인코딩된 10초짜리 영상이 170MB라고 가정해 보면 각각 다음과 같은 수치를 구할 수 있습니다.

  • 데이터 전송률: 170MB / 10초 = 17MB/s
  • 평균 비트 전송률: 170MB/s

비록 저 값이 같게 나오긴 했지만, 엄밀하게는 구분이 됩니다. 즉, Data rate는 모든 데이터가 완전히 기록된 순간에 구할 수 있는 값이고, 평균 비트 전송률은 재생 도중에도 구할 수 있는 값입니다.




마지막으로, 비디오/오디오 정보의 출력과,

Console.WriteLine($"# of VideoStreams: {mediaInfo.VideoStreams.Count}");
foreach (var stream in mediaInfo.VideoStreams)
{
    Console.WriteLine($"\tStream: {stream.ColorSpace} - {stream.CodecName} ({stream.Width} x {stream.Height}), {stream.AvgFrameRate:00.00} frames/second, Data rate {stream.BitRate}");
}

Console.WriteLine();
Console.WriteLine($"# of AudioStreams: {mediaInfo.AudioStreams.Count}");
foreach (var stream in mediaInfo.AudioStreams)
{
    Console.WriteLine($"\tStream: {stream.CodecName}, {stream.BitRate} bit/s, {stream.SampleRateHz} Hz, {stream.Channels} channels");
}

다음과 같이 동영상의 특정 시점(예: 2분)에 대한 스냅샷 이미지를 PNG 파일로 저장하는 것도 가능합니다.

// 확장자를 png로 지정 (이 외의 확장자를 지정해도 무시하고 png로 저장)
FFMpeg.Snapshot(inputPath, "test.png", new Size(stream.Width, stream.Height), TimeSpan.FromMinutes(2));

그리고 이런 일련의 과정 중에는 ffmpeg.exe/ffprobe.exe가 자식 프로세스로 아래와 같은 식의 명령줄로 실행됩니다.

"ffprobe.exe" -version
"ffprobe.exe" -loglevel error -print_format json -show_format -sexagesimal -show_streams -show_chapters "c:\fftemp\test.mp4" 
"ffmpeg.exe" -formats

"ffmpeg.exe" -codecs
"ffmpeg.exe" -encoders
"ffmpeg.exe" -decoders

"ffmpeg.exe" -ss 00:01:00.000 -i "c:\fftemp\test.mp4" -map 0:0 -c:v png -vframes 1  "test.png" -y

어떠세요? 간단하기도 하고, 아주 자세하게 동영상을 제어할 필요가 없는 시나리오에서는 제법 유용할 듯합니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/23/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
14015정성태9/22/202596닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/2025718닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20251433닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20251602닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20252112닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20252084오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20252637닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20252979닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20253237닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20253351Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20252855오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20253125오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20253394닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/20253515오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20257529닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가 [1]
14000정성태8/18/20253734오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20253508닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20253315닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20253842Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/20252878오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/20253104개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
13994정성태8/12/20252767오류 유형: 977. SQL Server - User, group, or role '...' already exists in the current database. (Microsoft SQL Server, Error: 15023)
13993정성태8/11/20253669오류 유형: 976. Microsoft.ML.OnnxRuntimeGenAI 패키지 사용 시 "cublasLt64_12.dll" which is missing. (Error 126: "The specified module could not be found.") 오류
13992정성태8/11/20253555닷넷: 2353. C# - Foundry Local을 이용한 gpt-oss-20b 모델 사용파일 다운로드1
13991정성태8/9/20253397오류 유형: 975. winget - Foundry Local 패키지 업데이트가 안 되는 문제
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...