NAT NAT - 25 days ago 6
Python Question

"Constant" audio waveform generation using python?

I'm looking for something to generate a "constant" audio waveform, which looks like this: A constant waveform

I have a set of analog datas:

12766:149
12786:0
13339:149
13359:0
13721:57
13741:0
15249:255
15269:0
15822:87


Where the format is
time_in_ms:amplitue
. I try to output them from a headphone jack.

I think that "constant waveform" shown above can be considered as a combination of multiple square waves with a very small frequency having different amplitudes, and last for 20ms.

Is that possible? What's out there that I can do this?

Answer

I guess you can simply write raw PCM audio frames into a .wav file using the wave module... https://docs.python.org/3/library/wave.html If your amplitude ranges from 0 to 255 inclusive it's probably easiest to create a wav file with a sampwidth of 1 (byte) and just write the amplitude as bytes into the sample frames.

with wave.open("test.wav","w") as w:
   w.setnchannels(1)
   w.setsampwidth(1)
   w.setframerate(4000)   # 4000 samples/sec
   w.writeframes(bytearray([100]*4000))   # 4000 samples of amplitude 100

The above creates a small file 'test.wav' that is a mono 8-bit audio waveform of constant amplitude 100. Change the code accordingly to write the amplitude values from your input file, adjust sample rate as required