Search code examples
python-2.7numpymachine-learningspeech

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()


Here's my code:

from scipy.io import wavfile

fName = 'file.wav'

fs, signal = wavfile.read(fName)
signal = signal / max(abs(signal))                 # scale signal
assert min(signal) >= -1 and max(signal) <= 1

And the error is:

Traceback (most recent call last):
  File = "vad.py", line 10, in <module>
    signal = signal / max(abs(signal))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()

Can anyone please help me solving this error..?

Thanks in advance..


Solution

  • The line that produces the error shouldn't give an error if your signal were 1D (ie, a mono audio file), so you probably have a stereo wav file and your signal has the shape (nsamples, 2). Here's a short example for a stereo signal:

    In [109]: x = (np.arange(10, dtype=float)-5).reshape(5,2)
    
    In [110]: x
    Out[110]: 
    array([[-5., -4.],
           [-3., -2.],
           [-1.,  0.],
           [ 1.,  2.],
           [ 3.,  4.]])
    
    In [111]: x /= abs(x).max(axis=0)  # normalize each channel independently
    
    In [112]: x
    Out[112]: 
    array([[-1. , -1. ],
           [-0.6, -0.5],
           [-0.2,  0. ],
           [ 0.2,  0.5],
           [ 0.6,  1. ]])
    

    Your next line will also give you trouble with a 2D array, so there try:

     (x>=-1).all() and (x<=1).all()