Files
audio2motion/scripts/GRID/run-10-speech-features-mel-align.py
T
2022-01-21 17:42:41 +08:00

74 lines
2.7 KiB
Python

import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
total_pid = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10" ]
if __name__ == "__main__":
path_data = Path('/yrfs/lsen/DATA/GRID/processing') # '../data/trinity/source'
v_ids = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_ids)} dir files, \n {v_ids[:3]}")
# for each speaker
for i, ipath_id in enumerate(v_ids):
id_name = ipath_id.stem
if id_name not in total_pid: continue
dir_video = path_data.joinpath(id_name)
v_dir_videos = sorted(dir_video.glob("*/video/video_orignal.mp4"))
print(f"\nid= {id_name}, Have {len(v_dir_videos)} video files, \n {v_dir_videos[:10]}")
# for each video
for iv, ipath_video in enumerate(v_dir_videos):
ipath_data = ipath_video.parent.parent
ipath_audio = ipath_data.joinpath("audio/audio_extract.wav")
ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy")
if ipath_save_feat.exists() or not ipath_audio.exists():
continue
# load trim audio
fps = 25
data, sr = librosa.load(str(ipath_audio), sr=16000) # 16000 = fps * 640 让这个sr是fps的整数,
hop_len = int(sr / fps)
n_fft = int(sr * 0.13) # default 2048
# print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}")
# melspectrogram
mel = librosa.feature.melspectrogram(y=data, sr=sr,
n_fft=n_fft, # FFT窗口的长度
hop_length=hop_len, # 帧移
win_length=n_fft, # 窗口长度,默认=n_fft
window="hann", # 加hanming窗
n_mels=27, # 滤波器组
fmin=0.0, fmax=8000)
mel = np.log(mel+1).T
print(f"sr={sr}, data ={data.shape}, mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}")
# align to video
if mel.shape[0] < 75:
print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}")
else:
mel_align = mel[:75, :]
# save
np.save(ipath_save_feat, mel_align)