Search code examples
python-3.xsox

python 3.8.6 sox example will not work, the conversions are not working, the out wave files are unplayable


has anyone made this following python sox example work:

the data conversations do not take place,

The output files are unplayable and look to contain 32 bit data

I think pysox may be passing the wrong format to sox or pysox and sox do not match. using python 3.8.6 in win 7 64 bit

no errors are shown, print statements show the data as we go


    import numpy as np
    import sox
    
        # sample rate in Hz
    sample_rate = 44100
    
        # generate a 1-second sine tone at 440 Hz
    y = np.sin(2 * np.pi * 440.0 * np.arange(sample_rate * 1.0) / sample_rate)
       
    
    #this print just prints first and last
    print(y)
    
          # create a transformer
    tfm = sox.Transformer()
    
        # shift the pitch up by 2 semitones
    tfm.pitch(2)
    
        # transform an in-memory array and return an array
    y_out = tfm.build_array(input_array=y, sample_rate_in=sample_rate)
    
    print(y,y_out)
    
        # instead, save output to a file
    tfm.build_file(
            input_array=y, sample_rate_in=sample_rate,
            output_filepath='./output/output.wav'
            
        )
        # create an output file with a different sample rate
    tfm.set_output_format(rate=8000)
    tfm.build_file(
            input_array=y, sample_rate_in=sample_rate,
            output_filepath='./output/output_8k.wav'
        )
    ```

Solution

  • set_output_format has quite a few parameters that can be set, beyond just rate. One of them is bits which appears to be exactly what you're looking for.

    tfm.set_output_format(bits=16)
    

    You could probably set it at the same time you're setting the rate:

    tfm.set_output_format(rate=8000, bits=16)