在Python中将波转换为分贝

she*_*der 3 python audio pyaudio pydub librosa

我在将样本数组转换为分贝时遇到问题。这是我尝试过的代码。

from pydub import AudioSegment
audio=AudioSegment.from_mp3('am_voice.mp3')
samples=audio.get_array_of_samples()
import math
def convert_to_decibel(arr):
    if arr!=0:
        return 10 * math.log10(abs(arr))    
    else:
        return -60
data=[convert_to_decibel(i) for i in samples]
Run Code Online (Sandbox Code Playgroud)

这将返回所有正数据。然而,分贝值应始终为负值。这是我要创建的数据:

percentile=np.percentile(data,[25,50,75])
print(f"1st Quartile : {percentile[0]}")
print(f"2nd Quartile : {percentile[1]}")
print(f"3rd Quartile : {percentile[2]}")
print(f"Mean : {np.mean(data)}")
print(f"Median : {np.median(data)}")
print(f"Standard Deviation : {np.std(data)}")
print(f"Variance : {np.var(data)}")
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

PS:我也尝试过 librosa 和其他库。

Tre*_*ees 5

假设信号的幅度为 a,则 就 而言0<a<1y=log10(a)将为-inf<y<0。负尖峰可以用一些负数代替,就像您所做的 -60 dB 一样。要获得负 dB 值,样本的值应小于 1。请注意,dB 级别表明与某些参考信号值的关系。音频(声学)信号由各种参考值组成,应将其指定为 ref。在数字音频信号中,样本大多指定为小于 1。术语 db Full Scale ( dbFS ) 用于数字音频信号中的 ref=1。下面是使用 -1 到 1 范围内的音频信号对代码进行的修改soundfile,这与库相反AudioSegment

from pydub import AudioSegment
import numpy as np
import soundfile as sfile
import math
import matplotlib.pyplot as plt
filename = 'Alesis-Sanctuary-QCard-Crickets.wav'
# https://freewavesamples.com/files/Alesis-Sanctuary-QCard-Crickets.wav

audio=AudioSegment.from_mp3(filename)
signal, sr = sfile.read(filename)
samples=audio.get_array_of_samples()
samples_sf=0
try:
    samples_sf = signal[:, 0]  # use the first channel for dual
except:
    samples_sf=signal  # for mono


def convert_to_decibel(arr):
    ref = 1
    if arr!=0:
        return 20 * np.log10(abs(arr) / ref)
        
    else:
        return -60

data=[convert_to_decibel(i) for i in samples_sf]
percentile=np.percentile(data,[25,50,75])
print(f"1st Quartile : {percentile[0]}")
print(f"2nd Quartile : {percentile[1]}")
print(f"3rd Quartile : {percentile[2]}")
print(f"Mean : {np.mean(data)}")
print(f"Median : {np.median(data)}")
print(f"Standard Deviation : {np.std(data)}")
print(f"Variance : {np.var(data)}")


plt.figure()
plt.subplot(3, 1, 1)
plt.plot(samples)
plt.xlabel('Samples')
plt.ylabel('Data: AudioSegment')

plt.subplot(3, 1, 2)
plt.plot(samples_sf)
plt.xlabel('Samples')
plt.ylabel('Data: Soundfile')
plt.subplot(3, 1, 3)
plt.plot(data)
plt.xlabel('Samples')
plt.ylabel('dB Full Scale (dB)')
plt.tight_layout()
plt.show()

Run Code Online (Sandbox Code Playgroud)

输出

1st Quartile : -51.7206201849085
2nd Quartile : -35.31427238781313
3rd Quartile : -22.110336232568464
Mean : -37.76500744850379
Median : -35.31427238781313
Standard Deviation : 18.848883199155107
Variance : 355.2803978553917
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述