Search code examples
pythonpython-3.xnumpywav

Numpy: Wav to list and then back again creates garbage


I'm using Python 3.7 and am currently developing a solution that requires me to convert a WAV file to a Numpy Array, then to a List, then back to an Array, and finally written again as a WAV file. Earlier today, it was able to convert and then reconvert with no issues. However, it is currently returning a WAV file that is listenable but is entirely static.

import numpy as np
import scipy.io.wavfile as wavfile

...

rate, data = wavfile.read(os.path.join(F_IN_FOLDER, f))
work = data.tolist()
out = np.array(work, dtype=np.float32)
wavfile.write(os.path.join(F_IN_FOLDER, f), rate, out)

The purpose of this code is so that, as a list, I can silence portions of the WAV file and then write over the original file. I am inexperienced with WAV files as well as the Numpy library, and if there is a more efficient way to this this, I'm interested in learning it.


Solution

  • I agree with @NilsWerner - you should be able to do everything as numpy array's and much faster than working with it as a list. I'm not sure what you mean by "silence", but assuming for the moment that this involves writing zeroes to particular parts of the array then you could do something like:

    # create an array of 1's (my sample test data)
    a = np.ones(10)
    
    # zero out a specific range of indices using standard numpy slice notation.
    a[5:8] = 0
    
    # check the result
    print(a)
    

    and get back

    [1. 1. 1. 1. 1. 0. 0. 0. 1. 1.]
    

    check out the numpy documentation at numpy slices and the related scipy documentation scipy indexing.