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

C# / Whisper 모델 - 동영상의 음성을 인식해 자동으로 SRT 자막 파일을 생성

테스트를 위해 우선 동영상 파일 먼저 구해 볼까요? ^^

"C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지)" 글에서 "https://youtu.be/90HFIm2Reqk" 동영상을 다운로드하면 비디오를 담은 mp4, 오디오를 담은 webm 파일과 그 2개를 합친 "...-final.mp4" 파일이 생성됩니다.

보통은 (video + audio가 모두 있는) mp4 파일만 있을 텐데요, 그런 경우에는 FFMpegCore를 사용해 mp4로부터 오디오를 분리해 내는 것부터 시작하면 됩니다.

// Install-Package FFMpegCore
using FFMpegCore;
string mp4FilePath = @"C:\temp\test_net_conf.mp4";
string mp3FilePath = @"C:\temp\test_net_conf.mp3"; // mp3 확장자 필수!

// ffmpeg -hide_banner -i test.webm -vn test.mp3
if (FFMpeg.ExtractAudio(mp4FilePath, mp3FilePath) == false)
{
    Console.WriteLine("invalid mp4 file");
    return;
}

/*
C:\temp> ffprobe -hide_banner test_net_conf.mp3
Input #0, mp3, from 'test_net_conf.mp3':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:40:59.57, start: 0.023021, bitrate: 128 kb/s
  Stream #0:0: Audio: mp3, 48000 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc58.91
*/

이렇게 생성한 mp3 파일의 Sample Rate는 다양하겠지만, 위의 경우에는 48kHz로 나오는데요, 아쉽게도 Whisper 모델은 16kHz 규격만 처리할 수 있기 때문에 포맷을 변환해 주어야 합니다. 마침 NAudio에서 이런 변환 기능도 제공하므로,

examples/NAudioResampleWav/Program.cs
; https://github.com/sandrohanea/whisper.net/blob/main/examples/NAudioResampleWav/Program.cs

아래와 같이 mp3 파일을 전처리할 수 있습니다.

// Install-Package NAudio
using NAudio.Wave;
using var fileStream = File.OpenRead(mp3FilePath);
using var wavStream = new MemoryStream();

using var reader = new Mp3FileReader(fileStream);
var resampler = new WdlResamplingSampleProvider(reader.ToSampleProvider(), 16000);
WaveFileWriter.WriteWavFileToStream(wavStream, resampler.ToWaveProvider16());

wavStream.Seek(0, SeekOrigin.Begin);

자, 그럼 MemoryStream에 담긴 내용을 Whisper 모델에 넘겨주면 되는데요, 아무래도 GgmlType.Base 모델은 빠르긴 해도 정확도가 너무 떨어지므로, GgmlType.LargeV1 모델을 사용해 다음과 같은 식으로 음성을 텍스트로 변환할 수 있습니다.

// Install-Package Whisper.net.AllRuntimes

var ggmlType = GgmlType.LargeV1;
var modelFileName = "ggml-large-v1.bin";

if (!File.Exists(modelFileName))
{
    await DownloadModel(modelFileName, ggmlType);
}

using var whisperFactory = WhisperFactory.FromPath(modelFileName);

// This section creates the processor object which is used to process the audio file, it uses language `auto` to detect the language of the audio file.
using var processor = whisperFactory.CreateBuilder()
    .WithLanguage("auto")
    .Build();

// This section processes the audio file and prints the results (start time, end time and text) to the console.
await foreach (var result in processor.ProcessAsync(wavStream))
{
    Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
}

/* 출력 결과
00:00:00->00:00:06.9200000:  [모든 이야기는 다음 주에 만나요]
00:00:06.9200000->00:00:09.7200000:  [모든 이야기는 다음 주에 만나요]
00:00:09.7200000->00:00:14.1200000:  네, 시작하도록 하겠습니다.
00:00:14.1200000->00:00:17.8400000:  저는 이번 세션 발표를 맡은
...[생략]...
00:40:18.5200000->00:40:22.5200000:  이 패턴에 친숙해지시는 걸 추천드린다고 말씀드리고 싶습니다.
00:40:22.5200000->00:40:34.5200000:  제 발표는 여기까지였고요. 궁금하신 점이 있거나 하시면 이 링크드인, 이렇게 질문해 보세요라고 얘기를 하면 보통 질문을 안 하시더라고요.
00:40:34.5200000->00:40:44.5200000:  링크드인 주소가 있으니까 통해서 연락 주시면 제가 답해 드릴 수 있는 범위에서 최선을 다해서 답을 해 드리도록 하겠습니다.
00:40:44.5200000->00:40:46.5200000:  네, 고맙습니다.
*/

출력 예시를 보면, 훌륭하게도 ^^ 음성이 인식된 시점의 시작 시간과 종료 시간이 함께 표시되는 것을 알 수 있습니다. 즉, 자막 파일을 위한 기본적인 정보가 모두 갖추어진 셈입니다.

이제 남은 것은 자막 파일의 포맷에 맞게 쓰기만 하면 되는데요, 여러 자막 포맷이 있지만 여기서는 SRT 포맷을 예로 들어,

SRT 파일 구조 
; https://docs.fileformat.com/ko/video/srt/

/*
1
00:05:00,400 --> 00:05:15,300
This is an example of
a subtitle.

2
00:05:16,400 --> 00:05:25,300
This is an example of
a subtitle - 2nd subtitle.
*/

간단한 도우미 클래스를 만든 후,

using System.Text;

public class SRTWriter : IAsyncDisposable
{
    FileStream _fs;
    int _index;

    public SRTWriter(string filePath)
    {
        _index = 0;
        _fs = File.OpenWrite(filePath);
    }

    public void Write(TimeSpan startTime, TimeSpan endTime, string text)
    {
        _index++;

        string timeLine = $"{_index}\n{startTime:hh\\:mm\\:ss\\,fff} --> {endTime:hh\\:mm\\:ss\\,fff}\n";
        byte [] buffer = Encoding.UTF8.GetBytes(timeLine);
        _fs.Write(buffer);

        string subTitle = $"{text}\n\n";
        buffer = Encoding.UTF8.GetBytes(subTitle);
        _fs.Write(buffer);
    }

    public ValueTask DisposeAsync()
    {
        _fs.DisposeAsync();
        return ValueTask.CompletedTask;
    }
}

Whisper.NET의 출력을 그대로 보내주면 됩니다.

// ...[생략]...

string srtPath = Path.ChangeExtension(mp4FilePath, ".srt");

File.WriteAllText(srtPath, string.Empty);

await using SRTWriter writer = new(srtPath);
await foreach (var result in processor.ProcessAsync(wavStream))
{
    Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
    writer.Write(result.Start, result.End, result.Text);
}

끝입니다. ^^ 실행해 보면, 가령 입력 파일이 test_net_conf.mp4 입력 파일이었다면 test_net_conf.srt 파일이 생성될 텐데요, 동영상 재생기를 통해 mp4 파일을 실행하면 다음과 같이 자막이 표시되는 것을 확인할 수 있습니다.

srt_from_video_1.png

게다가 Whisper 모델이 한국어뿐만 아니라 영어, 일본어 등을 지원하기 때문에, whisperFactory의 WithLanguage에 어떤 인자를 전달하느냐에 따라,

await using var processor = whisperFactory.CreateBuilder()
    .WithLanguage("ja") // 일본어로 번역
    .Build();

다국어 자막 파일을 (위의 경우에는 일본어로) 생성하는 것도 가능합니다.

srt_from_video_2.png

현재 GgmlType.LargeV1 모델 정도로도 꽤 괜찮은 인식률을 보여주기 때문에 이러한 방식으로 다국어 지원을 하는 것은 순전히 여러분이 소유한 GPU 성능에 달려 있다고 할 수 있습니다.

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




참고로, 아래의 동영상을 보면,

How I Transcribe Audio Locally with Whisper and .NET
; https://www.youtube.com/watch?v=H9kr7a78v44&ab_channel=StevanFreeborn

스티븐 프리본(Stevan Freeborn)이라는 분이 Whisper 모델을 사용해 동영상의 음성을 인식해 자막 파일을 생성하는 방법을 아주 상세히 설명해 주고 있습니다. 단지 그 영상의 소스 코드에서는 파일을 2분씩 끊어서 Whisper에 전달하고 있는데, 사실 그럴 필요가 없습니다. 왜냐하면 Azure OpenAI 서비스의 Whisper 모델에 대해서만 25MB 제약이 있는 것이고, 로컬에서 Whisper 모델을 사용하는 경우에는 그런 제약이 없기 때문입니다. 게다가 단순히 2분 단위로 끊으면 음성의 중간에 끊어질 수도 있기 때문에 가능하다면 단어 단위로 끊는 것이 더 좋습니다. ^^




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







[최초 등록일: ]
[최종 수정일: 10/12/2025]

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

비밀번호

댓글 작성자
 



2025-10-12 10시00분
umlx5h/LLPlayer
 - The media player for language learning, with dual subtitles, AI-generated subtitles, real-time translation, and more!
; https://github.com/umlx5h/LLPlayer
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13899정성태3/7/20255694스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20256419오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20258167닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20258159Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20257953Linux: 117. eBPF (bpf2go) - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20257210Linux: 116. eBPF (bpf2go) - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20256343Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
13892정성태2/24/20259347닷넷: 2325. C# - PowerShell과 연동하는 방법파일 다운로드1
13891정성태2/23/20256786닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법파일 다운로드1
13890정성태2/21/20257198닷넷: 2323. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(Win32 API)파일 다운로드1
13889정성태2/20/20258677닷넷: 2322. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(성능 카운터, WMI) [1]파일 다운로드1
13888정성태2/17/20258481닷넷: 2321. Blazor에서 발생할 수 있는 async void 메서드의 부작용
13887정성태2/17/202510261닷넷: 2320. Blazor의 razor 페이지에서 code-behind 파일로 코드를 분리 및 DI 사용법
13886정성태2/15/20256465VS.NET IDE: 196. Visual Studio - Code-behind처럼 cs 파일을 그룹핑하는 방법
13885정성태2/14/20258647닷넷: 2319. ASP.NET Core Web API / Razor 페이지에서 발생할 수 있는 async void 메서드의 부작용
13884정성태2/13/20259865닷넷: 2318. C# - (async Task가 아닌) async void 사용 시의 부작용파일 다운로드1
13883정성태2/12/20259083닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13882정성태2/10/20258131스크립트: 70. 파이썬 - oracledb 패키지 연동 시 Thin / Thick 모드
13881정성태2/7/20257333닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13880정성태2/5/202510728오류 유형: 947. sshd - Failed to start OpenSSH server daemon.
13879정성태2/5/20259579오류 유형: 946. Ubuntu - N: Updating from such a repository can't be done securely, and is therefore disabled by default.
13878정성태2/3/20259011오류 유형: 945. Windows - 최대 절전 모드 시 DRIVER_POWER_STATE_FAILURE 발생 (pacer.sys)
13877정성태1/25/20257601닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)파일 다운로드1
13876정성태1/25/20259266닷넷: 2314. C# - ProcessStartInfo 타입의 Arguments와 ArgumentList파일 다운로드1
13875정성태1/24/20256851스크립트: 69. 파이썬 - multiprocessing 패키지의 spawn 모드로 동작하는 uvicorn의 workers
13874정성태1/24/20258865스크립트: 68. 파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...