IndexError:试图绘制.wav文件的谱图时数组索引太多
问题描述:
我想绘制.wav文件的谱图。 下面的代码行为方式的一个奇怪的事情是它可以在一些.wav文件上工作,并在其他的文件上失败。我怀疑这是因为一些.wav文件的频道数量与其他频道不同。不过,我不知道如何确定一个.wav文件包含多少个通道。我已经在发布我的问题之前看过这个堆栈溢出帖子:What is a channel in a .wav file format?Do all channels play simultaneaously when a wav file is played?IndexError:试图绘制.wav文件的谱图时数组索引太多
我已经粘贴了下面的一个方法,试图通过filepath(fileNameToSaveTo)将文件路径(myAudio)转换为jpg。
def individualWavToSpectrogram(myAudio, fileNameToSaveTo):
print(myAudio)
#Read file and get sampling freq [ usually 44100 Hz ] and sound object
samplingFreq, mySound = wavfile.read(myAudio)
#Check if wave file is 16bit or 32 bit. 24bit is not supported
mySoundDataType = mySound.dtype
#We can convert our sound array to floating point values ranging from -1 to 1 as follows
mySound = mySound/(2.**15)
#Check sample points and sound channel for duel channel(5060, 2) or (5060,) for mono channel
mySoundShape = mySound.shape
samplePoints = float(mySound.shape[0])
#Get duration of sound file
signalDuration = mySound.shape[0]/samplingFreq
#If two channels, then select only one channel
mySoundOneChannel = mySound[:,0]
#Plotting the tone
# We can represent sound by plotting the pressure values against time axis.
#Create an array of sample point in one dimension
timeArray = numpy.arange(0, samplePoints, 1)
#
timeArray = timeArray/samplingFreq
#Scale to milliSeconds
timeArray = timeArray * 1000
#Plot the tone
plt.plot(timeArray, mySoundOneChannel, color='Black')
#plt.xlabel('Time (ms)')
#plt.ylabel('Amplitude')
print("trying to save")
plt.savefig('/Users/billybobjoe/Desktop/SavedSpecs' + fileNameToSaveTo + '.jpg')
print("saved")
plt.show()
这产生对我的一些.wav文件 线57,下面的错误在individualWavToSpectrogram mySoundOneChannel =为mySound [:,0] IndexError:用于阵列太多索引
的代码行失败是
mySoundOneChannel = mySound[:,0]
如何检查.wav文件具有信道的数量,以及如何设置mySoundOneChannel据此?
答
据我所知,如果存在多个通道,则数据数组mySound
将具有形状(nSamples, nChannels)
。如果有一个频道,mySound
将有形状(nSamples,)
。
在这里,您的音频文件必须只有一个通道,因此您不能将它编入索引,就像它是2D数组一样。
因此,你应该能够用东西来取代
mySoundOneChannel = mySound[:,0]
像
if len(mySound.shape) > 1:
mySoundOneChannel = mySound[:,0]
else:
mySoundOneChannel = mySound
为了获得信道的数量,你应该能够做到:
if len(mySound.shape) > 1:
nChannels = mySound.shape[1]
else:
nChannels = 1