2017-06-28 5 views
0

J'essaie de tracer un spectrogramme d'un fichier .wav. La chose étrange à propos de la façon dont le code ci-dessous se comporte est qu'il fonctionne sur certains fichiers .wav et échoue sur d'autres. Je soupçonne que c'est parce que certains fichiers .wav ont un nombre différent de canaux par rapport aux autres. Cependant je n'ai aucune idée comment déterminer combien de canaux un fichier .wav contient. J'ai regardé ce post de débordement de pile avant de poster ma question: What is a channel in a .wav file format?Do all channels play simultaneaously when a wav file is played?IndexError: trop d'indices pour le tableau en essayant de tracer un spectrogramme d'un fichier .wav

J'ai collé une de mes méthodes ci-dessous qui essaye de convertir un chemin de fichier (myAudio) en jpg avec filepath (fileNameToSaveTo).

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() 

Cela produit l'erreur suivante sur certains de mes fichiers .wav ligne 57, dans individualWavToSpectrogram mySoundOneChannel = mySound [:, 0] IndexError: trop d'indices pour tableau

La ligne de code qui échoue est

mySoundOneChannel = mySound[:,0] 

Comment puis-je vérifier le nombre de canaux qu'un fichier .wav a, et comment puis-je configurer mySoundOneChannel en conséquence?

Répondre

0

Pour autant que je sache, le tableau de données mySound aura la forme (nSamples, nChannels) s'il y a plusieurs canaux. S'il y a un canal, mySound aura la forme (nSamples,).

Ici, votre fichier audio doit avoir un seul canal, et vous ne pouvez donc pas l'indexer comme s'il s'agissait d'un tableau 2D.

Par conséquent, vous devriez être en mesure de remplacer

mySoundOneChannel = mySound[:,0] 

avec quelque chose comme

if len(mySound.shape) > 1: 
    mySoundOneChannel = mySound[:,0] 
else: 
    mySoundOneChannel = mySound 

Pour obtenir le nombre de canaux, vous devriez être en mesure de le faire:

if len(mySound.shape) > 1: 
    nChannels = mySound.shape[1] 
else: 
    nChannels = 1