gpt4 book ai didi

python - 如何从Python中的频谱图中获取注释(频率及其时间)?

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:17 24 4
gpt4 key购买 nike

我正在尝试用Python编写一个程序,我可以从中上传音乐文件并从此文件中获取音符(在钢琴上)。我创建了一个Spectrogram ,现在我怎样才能从中获得频率呢?如何修复频谱图(我有一半的频谱图有镜面反射)?我需要像 this 这样的东西。 Here是我的代码。

import numpy as np
from matplotlib import pyplot as plt
import scipy.io.wavfile as wav
from numpy.lib import stride_tricks

""" short time fourier transform of audio signal """
def stft(sig, frameSize, overlapFac=0.5, window=np.hanning):
win = window(frameSize)
hopSize = int(frameSize - np.floor(overlapFac * frameSize))

# zeros at beginning (thus center of 1st window should be for sample nr. 0)
samples = np.append(np.zeros(np.floor(frameSize/2.0)), sig)
# cols for windowing
cols = np.ceil((len(samples) - frameSize) / float(hopSize)) + 1
# zeros at end (thus samples can be fully covered by frames)
samples = np.append(samples, np.zeros(frameSize))

frames = stride_tricks.as_strided(samples, shape=(cols, frameSize), strides=(samples.strides[0]*hopSize, samples.strides[0])).copy()
frames *= win

return np.fft.rfft(frames)

""" scale frequency axis logarithmically """
def logscale_spec(spec, sr=44100, factor=20.):
timebins, freqbins = np.shape(spec)

scale = np.linspace(0, 1, freqbins) ** factor
scale *= (freqbins-1)/max(scale)
scale = np.unique(np.round(scale))

# create spectrogram with new freq bins
newspec = np.complex128(np.zeros([timebins, len(scale)]))
for i in range(0, len(scale)):
if i == len(scale)-1:
newspec[:,i] = np.sum(spec[:,scale[i]:], axis=1)
else:
newspec[:,i] = np.sum(spec[:,scale[i]:scale[i+1]], axis=1)

# list center freq of bins
allfreqs = np.abs(np.fft.fftfreq(freqbins*2, 1./sr)[:freqbins+1])
freqs = []
for i in range(0, len(scale)):
if i == len(scale)-1:
freqs += [np.mean(allfreqs[scale[i]:])]
else:
freqs += [np.mean(allfreqs[scale[i]:scale[i+1]])]

return newspec, freqs

""" plot spectrogram"""
def plotstft(audiopath, binsize=2**10, plotpath=None, colormap="jet"):
samplerate, samples = wav.read(audiopath)
s = stft(samples, binsize)

sshow, freq = logscale_spec(s, factor=1.0, sr=samplerate)
ims = 20.*np.log10(np.abs(sshow)/10e-6) # amplitude to decibel

timebins, freqbins = np.shape(ims)

plt.figure(figsize=(15, 7.5))
plt.imshow(np.transpose(ims), origin="lower", aspect="auto", cmap=colormap, interpolation="none")
plt.colorbar()

plt.xlabel("time (s)")
plt.ylabel("frequency (Hz)")
plt.xlim([0, timebins-1])
plt.ylim([0, freqbins])

xlocs = np.float32(np.linspace(0, timebins-1, 5))
plt.xticks(xlocs, ["%.02f" % l for l in ((xlocs*len(samples)/timebins)+(0.5*binsize))/samplerate])
ylocs = np.int16(np.round(np.linspace(0, freqbins-1, 10)))
plt.yticks(ylocs, ["%.02f" % freq[i] for i in ylocs])

if plotpath:
plt.savefig(plotpath, bbox_inches="tight")
else:
plt.show()

plt.clf()

plotstft("Sound/piano2.wav")

最佳答案

您描述的音频转录问题是音乐信息检索 (MIR) 研究社区中的一个众所周知的问题。这不是一个容易解决的问题,它由两个方面组成:

  • 检测音调频率通常很困难,因为谐波的出现以及音符经常滑入(可以检测到 C# 而不是 C),此外还有调音差异。

  • 节拍检测:音频表演通常不会准确地及时播放,因此找到实际的开始可能很棘手。

一种有前途的新方法是使用深度神经网络来解决这个问题,例如:

Boulanger-Lewandowski, N.、Bengio, Y. 和 Vincent, P. (2012)。 Modeling temporal dependencies in high-dimensional sequences: Application to polyphonic music generation and transcription 。 arXiv 预印本 arXiv:1206.6392。

更多信息:

Poliner, G. E.、Ellis, D. P.、Ehmann, A. F.、Gómez, E.、Streich, S. 和 Ong, B. (2007)。音乐音频的旋律转录:方法和评估。 IEEE 音频、语音和语言处理汇刊,15(4), 1247-1256。

关于python - 如何从Python中的频谱图中获取注释(频率及其时间)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com