Baz
Baz

Reputation: 13185

Normalise a wave file

I wish to normalise a 16 bit mono wave file. Is this the correct approach?

import wave
w = wave.open("s.wav", 'rb')
data = [struct.unpack("<h",w.readframes(1))[0] for i in range(w.getnframes())]
f = 0x8000/max((abs(i) for i in data))
data = b''.join(struct.pack("<h",int(i*f)) for i in data)

Upvotes: 2

Views: 706

Answers (1)

Jorge Torres
Jorge Torres

Reputation: 1465

I guess that by normalizing what you want to do is fill as much of the dynamic range of the 16-bits.

I would use 0x7FFF instead of 0x8000 because if your signal has a saturated peak on the positive side, you will overflow the positive side. For example, if your signal peak is 0x7FFF (the maximum positive that can be stored on a 16-bit signed variable), then f = 0x8000 / 0x7FFF, this would give a value that overflows the 16-bit integer.

By using 0x7FFF you will never use the "maximum" negative value, but is safer.

Upvotes: 4

Related Questions