Convert 16 bit PCM data into numpy array of amplitudes

Viewed 434

I may not be using the right terminology here. I have a numpy array like:

array([ 82, 73, 70, ..., 1, 230, 1], dtype=uint8)

It's supposedly in 16 bit PCM format.

I need to turn this into a numpy audio waveform. And in case that's not the right terminology, I'll explain really well what that is: literally the sound wave amplitudes at some sample rate.

I also need do it as fast as possible with Python.

2 Answers

That is indeed, literally the sound wave amplitudes at some sample rate. But stored in a np.uint8 dtype. For example, if you want to hear it in a Jupyter Notebook, you can try:

import numpy as np
s = np.array([ 82, 73, 70, 2, 1, 230, 1], dtype=np.uint8)

from IPython.display import Audio
Audio(s, rate=22050)

then you can hear your sound.

jupyter notebook screenshot

Reshape your array of n samples to new shape(n/2, 2) Multiply second column by 256 (most significant byte) Sum pairs into 16 bit value

a = np.array([ 0x82, 0x73, 0x70, 0x1, 0x30, 0x1], dtype=np.uint8)
b = a.reshape(-1,2)*np.array([1,256], np.uint16)
c = b.sum(axis=1)

print(hex(c[0])) # '0x7382'
print(hex(c[1])) # '0x170'
print(hex(c[2])) # '0x130'
Related