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
정성태

... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13522정성태1/11/202416119닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/202413793닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/202414549오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....' [1]
13519정성태1/10/202413455닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/202415189닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/202412846스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/202414887닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/202413097닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/202412967개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/202414845닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/202415422개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/202414443닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/202414665닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/202415627오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/202417364오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/202415922닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/202313352닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/202317212닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/202318520닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/202314890Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/202316273닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/202315222개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/202315803디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/202316335닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/202316183오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/202313559Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...