# Applying a mathematical function to a 16-bit Python array

I am using scipy.io.wavfile to read a WAV file and playing it with pyaudio. Before the numpy array is written to a string and output through pyaudio, I would like to be able to apply some sort of function (sin, cos, etc.) to the 16-bit numpy array.

Does anyone have any experience doing something like this? Should I convert to float, apply the function to the float data, then convert back? I am also aware of fixed point arithmetic, but not sure if I can apply it here.

• It depends on what kind of processing you want to apply (I assume it is not any prototyping of algorithms for a DSP chip). Generally it's OK to convert your samples to floats and process everything using them. If you want to save the filtered samples back to int16, then just set the appropriate dtype of your array and don't worry about conversion. On the other hand if you want to play back the result using pyaudio then simply set the stream to be a float. pyaudio + *numpy*/*scipy is a very good choice.
– jojeck
Commented May 26, 2015 at 8:57
• "I would like to be able to apply some sort of function (sin, cos, etc.) to the 16-bit numpy array." You want to distort it? Commented Jul 25, 2015 at 4:31
• Yeah, but in a specific way. Commented Jul 25, 2015 at 13:12

If you're doing ANY audio signal processing in python, I heartily recommend librosa. Your scipy route will work (read as float, process, playback), but it is less direct. Also, I recommend sticking with float, as fixed-point work is more relevant if your code is running on an embedded/mobile system sans-FPU.

You can pip install librosa and get applying math functions quickly. Check out the introduction ipython notebook. Additionally, if you're doing more serious work, there is great integration with scikit-learn machine learning pipelines.

To get you started your code might look like this:

import librosa
import numpy as np