Python中读取的声音文件和波形文件之间的大小差异

2024-05-06 10:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现读取带有soundfilewavefile的wav文件之间的幅度响应存在问题。以下是不同的图:

enter image description here

你能告诉我需要在wavefile.read中调整什么以获得与soundfile.read相同的大小吗

以下是我使用的代码:

import os
import matplotlib.pyplot as plt
from matplotlib import transforms
import numpy as np
import soundfile as sf

import scipy.io.wavfile as wavfile

from matplotlib.gridspec import GridSpec

input_file1 = (r'G:/file.wav')

plt.subplot(211)
a, b = sf.read(input_file1);

pxx, fs = plt.psd(a, 512, b)
plt.semilogx(fs, 10*np.log10(pxx))
plt.title('Sound File Read')
plt.grid(which='major', axis='both', color='g', linestyle='-', alpha=0.4)
plt.grid(which='minor', axis='x', color='g', linestyle='-', alpha=0.1)

  
plt.subplot(212)
sample_rate, signal1 = wavfile.read(input_file1)
Pxx, freq = plt.psd(signal1, 512, sample_rate)
plt.semilogx(freq, 10*np.log10(Pxx))
plt.grid(which='major', axis='both', color='g', linestyle='-', alpha=0.4)
plt.grid(which='minor', axis='x', color='g', linestyle='-', alpha=0.1)
plt.title('Wavfile File Read')
plt.ylabel('PSD')

plt.xlabel('Frequency (Hz)')

# set the spacing between subplots
plt.tight_layout()

plt.show()

Here is a link to an example .wav file.

谢谢


1条回答
网友
1楼 · 发布于 2024-05-06 10:36:09

根据您报告的两个值,它确实看起来像soundfile.read给了您一个介于-1和1之间的float64数组,而wavfile.io.read给了您一个介于-2147483648和2147483647之间的int32数组(-4850432/2147483648=-0.00225866)。您可以使用以下命令从int_float_数组创建规范化的float_数组:

def normalize(signal1):
    try:
        intinfo = np.iinfo(signal1.dtype)
        return signal1 / max( intinfo.max, -intinfo.min )

    except ValueError: # array is not integer dtype
        return signal1 / max( signal1.max(), -signal1.min() )

相关问题 更多 >