Last active
December 27, 2023 07:15
-
-
Save tam17aki/f9d955d178128cf139e935a2756a340b to your computer and use it in GitHub Desktop.
Estimation of phase spectrum based on the Griffin-Lim algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Griffin-Lim algorithm. | |
Copyright (C) 2023 by Akira Tamamori | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import librosa | |
import numpy as np | |
def gla(amp_spec, cfg, init_spec=None): | |
"""Estimation of phase spectrum based on the Griffin-Lim algorithm.""" | |
hop_length = cfg.feature.hop_length | |
frame_length = cfg.feature.frame_length | |
n_fft = cfg.feature.n_fft | |
iter = cfg.feature.gla_iter | |
amp_spec = amp_spec.T | |
for i in range(iter): | |
if i == 0: | |
# 初回は乱数で初期化 or 初期位相スペクトルで初期化 | |
if init_spec is None: | |
phase_spec = np.random.rand(*amp_spec.shape) | |
else: | |
phase_spec = init_spec.T | |
else: | |
# 振幅スペクトルと推定された位相スペクトルから複素スペクトログラムを復元 | |
recovered_spec = amp_spec * np.exp(1j * phase_spec) | |
# 短時間フーリエ逆変換で音声を復元 | |
recovered = librosa.istft( | |
recovered_spec, | |
n_fft=n_fft, | |
hop_length=hop_length, | |
win_length=frame_length, | |
) | |
# 復元音声から複素スペクトログラムを再計算 | |
complex_spec = librosa.stft( | |
recovered, | |
n_fft=n_fft, | |
hop_length=hop_length, | |
win_length=frame_length, | |
) | |
# 初回以降は計算済みの複素スペクトログラムから位相スペクトルを推定 | |
phase_spec = np.angle(complex_spec) | |
return phase_spec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment