Post

03.19 Progress

03.19 Progress
  • 연구 계획서 작성
  • Python 오디오 기초 처리 실습

환경 세팅

GPU 확인

1
nvidia-smi

image-5

1단계 : Conda 가상환경 생성

1
2
conda create -n game-ebd python=3.10 -y 
conda activate game-ebd

2단계 : PyTorch 설치(CUDA 12.1호환)

딥러닝 프레임워크

1
python -m pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121

3단계 : 오디오 처리 + 분석 라이브러리 설치

1
python -m pip install librosa numpy matplotlib scipy scikit-learn

4단계: ffmpeg 설치

소리만 분리해서 wav 파일로 뽑을 때 사용

1
conda install -c conda-forge ffmpeg -y

5단계: 설치 확인

전부 설치가 끝나면 아래 명령어로 핵심 항목들이 제대로 잡혔는지 확인

1
2
3
4
5
6
7
8
9
10
11
12
13
python -c "
import torch
print('PyTorch:', torch.__version__)
print('CUDA 사용 가능:', torch.cuda.is_available())
print('GPU 개수:', torch.cuda.device_count())
print('GPU 이름:', torch.cuda.get_device_name(0))

import librosa
print('librosa:', librosa.__version__)

import numpy
print('numpy:', numpy.__version__)
"

output

1
2
3
4
5
6
PyTorch: 2.5.1+cu121
CUDA 사용 가능: True
GPU 개수: 2
GPU 이름: NVIDIA TITAN RTX
librosa: 0.11.0
numpy: 2.2.6
1
ffmpeg -version | head -1

output

1
ffmpeg version 8.0 Copyright (c) 2000-2025 the FFmpeg developers

개념

MFCC 추출 과정

MFCC는 오디오 신호에서 단계적으로 정보를 변환해가는 과정 image-9 1단계 - 프레임 분할: 오디오를 약 0.02초(20ms)단위로 잘게 쪼갠다. 이 짧은 구간 안에서는 소리가 거의 일정하다고 가정.

2단계 - FFT: 각 프레임에 FFT를 적용해서 “이 0.02초 안에 어떤 주파수 성분이 얼마나 들어있는가”를 알아낸다. waveform은 시간축이었는데, FFT를 거치면서 주파수축으로 바뀐다. 예를 들어 총소리는 넓은 주파수 대역에 에너지가 퍼져있고, BGM의 저음 베이스는 낮은 주파수에 에너지가 몰려있다.

3단계 - Mel 필터: 사람 귀는 저주파(낮은 소리)에 민감하고 고주파(높은 소리)는 잘 구분 못한다. Mel 필터는 이 특성을 반영해서 저주파는 촘촘하게, 고주파는 뭉뚱그려서 본다. 불필요한 세부 정보를 버리고 “사람이 인지하는 차이”에 집중하는 것이다.

4단계 - 로그: 소리 에너지는 범위가 어마어마하게 넓어서(속삭임 vs 폭발음), 로그를 씌워서 범위를 압축한다. 데시벨(dB)을 쓰는 것과 같은 원리다.

5단계 - DCT: 마지막으로 DCT를 적용해서 상위 13개 계수만 뽑는다. 이게 해당 프레임의 “소리 지문”역할을 하는 MFCC다.

왜 코사인 유사도를 보는가?

image-11

SSM으로 어떻게 연결되는가?

image-12

실습

librosa.load()로 오디오 불러오기, 파형(waveform) 그리기

youtube id : mRySWOleYPM game : battleground genre : fps, battleroyale

영상 다운로드

1
2
python -m pip install yt-dlp
yt-dlp -f "mp4" -o "./data/video/battle_ground_play_video.mp4" "https://www.youtube.com/watch?v=mRySWOleYPM"

오디오 추출

1
ffmpeg -i ./data/video/battle_ground_play_video.mp4 -vn -ar 22050 ./data/audio/battle_ground_play_audio.wav

Python으로 오디오 불러오기 + waveform 시각화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np

# 오디오 로드
y, sr = librosa.load('audio.wav', sr=22050)

# 기본 정보 출력
print(f'샘플레이트: {sr}')
print(f'총 샘플 수: {len(y)}')
print(f'재생 시간: {len(y)/sr:.1f}초')

# waveform 시각화
plt.figure(figsize=(14, 4))
librosa.display.waveshow(y, sr=sr)
plt.title('Waveform')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.savefig('waveform.png', dpi=150)
plt.show()

output image-6 y축 : Amplitude - 진폭 x축 : Time - 시간 값이 0이면 조용한 구간, 위 아래로 크게 흔들리면 시끄러운 구간 => 단순히 소리의 크기만 담고 있음.

MFCC 추출 및 시각화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np

# 오디오 로드
y, sr = librosa.load('../data/audio/battle_ground_play_audio.wav', sr=22050)

# MFCC 추출
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)

# 기본 정보 출력
print(f'MFCC shape: {mfcc.shape}')
print(f'계수 개수: {mfcc.shape[0]}')
print(f'프레임 수: {mfcc.shape[1]}')

# MFCC 히트맵 시각화
plt.figure(figsize=(14,5))
librosa.display.specshow(mfcc, sr=sr, x_axis='time', hop_length=512)
plt.colorbar()
plt.title('MFCC')
plt.xlabel('Time (s)')
plt.ylabel('MFCC Coefficients')
plt.tight_layout()
plt.savefig('mfcc.png', dpi=150)
plt.show()

output image-7

  • 행 (n_mfcc=13) → 오디오의 특성을 요약한 13개 계수
  • 열 (프레임 수) → 시간축을 일정 간격으로 쪼갠 것 waveform이 “소리가 얼마나 큰가”만 보여줬다면, MFCC는 “이 소리가 어떤 소리인가”를 알려준다. 같은 크기의 총소리와 BGM이 있어도, MFCC값은 다르게 나온다. 소리의 톤, 질감을 숫자로 잡아내는 것.

Self-Similarity Matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import librosa
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity

# 오디오 로드 + MFCC 추출
y, sr = librosa.load('audio.wav', sr=22050)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)

# MFCC 전치: (프레임 수, 13) 형태로 변환
# 각 행이 한 시점의 소리 특성 벡터가 됨
mfcc_T = mfcc.T

print(f'프레임 수: {mfcc_T.shape[0]}')
print(f'각 프레임의 특성 벡터 차원: {mfcc_T.shape[1]}')

# 코사인 유사도 행렬 계산
sim_matrix = cosine_similarity(mfcc_T)

print(f'유사도 행렬 shape: {sim_matrix.shape}')

# 시각화
plt.figure(figsize=(10, 8))
plt.imshow(sim_matrix, cmap='magma', origin='lower')
plt.colorbar(label='Cosine Similarity')
plt.title('MFCC Cosine Similarity Matrix')
plt.xlabel('Frame')
plt.ylabel('Frame')
plt.tight_layout()
plt.savefig('similarity_matrix.png', dpi=150)
plt.show()

실행 중 killed 발생

1
y, sr = librosa.load('audio.wav', sr=22050, duration=60)

초반 60초만 잘라서 보기

output image-8

Macro Meso SSM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import librosa
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity

# 전체 오디오 로드
y, sr = librosa.load('audio.wav', sr=22050)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
mfcc_T = mfcc.T  # (프레임 수, 13)

print(f'전체 프레임 수: {mfcc_T.shape[0]}')

def make_ssm(features, window_sec, hop_sec, sr=22050, hop_length=512):
    """윈도우 단위로 평균내서 SSM 생성"""
    frames_per_sec = sr / hop_length
    win_frames = int(window_sec * frames_per_sec)
    hop_frames = int(hop_sec * frames_per_sec)
    
    segments = []
    for start in range(0, len(features) - win_frames, hop_frames):
        segment = features[start:start + win_frames].mean(axis=0)
        segments.append(segment)
    
    segments = np.array(segments)
    print(f'윈도우 {window_sec}s, 홉 {hop_sec}s → 세그먼트 수: {len(segments)}')
    return cosine_similarity(segments)

# Macro SSM (20초 윈도우, 5초 홉)
ssm_macro = make_ssm(mfcc_T, window_sec=20, hop_sec=5)

# Meso SSM (3초 윈도우, 1초 홉)  
ssm_meso = make_ssm(mfcc_T, window_sec=3, hop_sec=1)

# 시각화
fig, axes = plt.subplots(1, 2, figsize=(16, 7))

axes[0].imshow(ssm_macro, cmap='magma', origin='lower')
axes[0].set_title('Macro SSM (20s window)')
axes[0].set_xlabel('Segment')
axes[0].set_ylabel('Segment')

axes[1].imshow(ssm_meso, cmap='magma', origin='lower')
axes[1].set_title('Meso SSM (3s window)')
axes[1].set_xlabel('Segment')
axes[1].set_ylabel('Segment')

plt.tight_layout()
plt.savefig('ssm_comparison.png', dpi=150)
plt.show()

output image-13

Checkboard

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import numpy as np
import matplotlib.pyplot as plt
import librosa
from sklearn.metrics.pairwise import cosine_similarity
from scipy.signal import find_peaks


# 오디오 로드 + MFCC 추출
y, sr = librosa.load('../data/audio/battle_ground_play_audio.wav', sr=22050)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)

# MFCC 전치: (프레임 수, 13) 형태로 변환
# 각 행이 한 시점의 소리 특성 벡터가 됨
mfcc_T = mfcc.T

print(f'프레임 수: {mfcc_T.shape[0]}')
print(f'각 프레임의 특성 벡터 차원: {mfcc_T.shape[1]}')

def make_ssm(features, window_sec, hop_sec, sr=22050, hop_length=512):
    """윈도우 단위로 평균내서 SSM 생성"""
    frames_per_sec = sr / hop_length
    win_frames = int(window_sec * frames_per_sec)
    hop_frames = int(hop_sec * frames_per_sec)

    segments = []
    for start in range(0, len(features) - win_frames, hop_frames):
        segment = features[start:start + win_frames].mean(axis=0)
        segments.append(segment)

    segments = np.array(segments)
    print(f'윈도우 {window_sec}s, 홉 {hop_sec}s → 세그먼트 수: {len(segments)}')
    return cosine_similarity(segments)


def checkerboard_kernel(size):
    """Checkerboard 커널 생성"""
    kernel = np.ones((size, size))
    for i in range(size):
        for j in range(size):
            if (i < size//2 and j < size//2) or (i >= size//2 and j >= size//2):
                kernel[i, j] = 1
            else:
                kernel[i, j] = -1
    return kernel

def compute_novelty(ssm, kernel_size=16):
    """SSM 대각선을 따라 novelty score 계산"""
    kernel = checkerboard_kernel(kernel_size)
    half = kernel_size // 2
    n = ssm.shape[0]
    novelty = np.zeros(n)
    
    for i in range(half, n - half):
        # 대각선 위 커널 크기만큼 영역 추출
        patch = ssm[i-half:i+half, i-half:i+half]
        novelty[i] = np.sum(patch * kernel)
    
    # 0~1로 정규화
    novelty = np.maximum(novelty, 0)
    if novelty.max() > 0:
        novelty /= novelty.max()
    
    return novelty

# Macro SSM (20초 윈도우, 5초 홉)
ssm_macro = make_ssm(mfcc_T, window_sec=20, hop_sec=5)

# Meso SSM (3초 윈도우, 1초 홉)  
ssm_meso = make_ssm(mfcc_T, window_sec=3, hop_sec=1)
# 시각화
fig, axes = plt.subplots(3, 2, figsize=(18, 12))

macro_hop = 5   # Macro: 5초 hop
meso_hop = 1    # Meso: 1초 hop

# 왼쪽: Macro SSM
for idx, ks in enumerate([8, 16, 32]):
    novelty = compute_novelty(ssm_macro, kernel_size=ks)
    peaks, _ = find_peaks(novelty, height=0.3, distance=5)
    time_axis = np.arange(len(novelty)) * macro_hop / 60
    peak_times = peaks * macro_hop / 60
    
    axes[idx][0].plot(time_axis, novelty, color='coral')
    axes[idx][0].plot(peak_times, novelty[peaks], 'v', color='red', markersize=10)
    axes[idx][0].set_title(f'Macro | kernel={ks} → Boundary {len(peaks)}개')
    axes[idx][0].set_ylabel('Novelty')
    axes[idx][0].set_xlabel('Time (min)')

# 오른쪽: Meso SSM
for idx, ks in enumerate([16, 32, 64]):
    novelty = compute_novelty(ssm_meso, kernel_size=ks)
    peaks, _ = find_peaks(novelty, height=0.3, distance=10)
    time_axis = np.arange(len(novelty)) * meso_hop / 60
    peak_times = peaks * meso_hop / 60
    
    axes[idx][1].plot(time_axis, novelty, color='teal')
    axes[idx][1].plot(peak_times, novelty[peaks], 'v', color='red', markersize=10)
    axes[idx][1].set_title(f'Meso | kernel={ks} → Boundary {len(peaks)}개')
    axes[idx][1].set_ylabel('Novelty')
    axes[idx][1].set_xlabel('Time (min)')


plt.tight_layout()
plt.savefig('kernel_size_comparison.png', dpi=150)
plt.show()

output image-14kernel size에 따라 보는 범위가 달라진다.

BEATs 모델로 임베딩 추출

BEATs 다운로드

1
2
3
# BEATs 코드 클론
git clone https://github.com/microsoft/unilm.git
cd unilm/beats

unilm/beats/README.md at master · microsoft/unilm checkpoint 다운로드 후 이동


기존 실습 코드들을 재활용할 수 있도록 리팩토링

THECOCKTAILFORKPROBLEM: THREE-STEMAUDIOSEPARATIONFORREAL-WORLDSOUNDTRACKS 활용하기

darius522/dnr-utils: Utility tools for the “Divide and Remaster” dataset, introduced as part of the Cocktail Fork problem paper: https://arxiv.org/abs/2110.09958

그래서 어떻게 할 건지 생각해보기.. 우선 데이터 정리 먼저 진행.

  • FPS, Action RPG, Puzzle 3개로 고정.

영상 길이를 1분 이내로 잡아야 할 것 같다. => 영상이 길어지면 annotation도 어렵고, 나중에 추론 시 컴퓨팅 자원의 부담도 커진다.

장르대표 게임경계 신호 특성역할
FPSValorant, Apex Legends전투/이동 경계 명확, 오디오 강함방법론 유효 케이스
액션 RPGElden Ring 등전투/탐색/컷씬 혼재, 중간 복잡도일반 케이스
퍼즐Portal 2 등BGM 단조로움, 경계 애매한계 분석 케이스

문제는 데이터셋 annotation을 어떤 기준으로 할 것인가?


This post is licensed under CC BY 4.0 by the author.