Search code examples
pythonpyaudio

Packing generated audio data from float to str


The task is to generate audio data and let the pyaudio play them. In steps:
1. Generate the sound data
2. Convert them to strings so the
3. pyaudio stream could play them

Number one is clear and all works with e.g. this code:

for x in xrange(NUMBEROFFRAMES):
    WAVEDATA = WAVEDATA+chr(int(math.sin(2*x/((BITRATE/FREQUENCY)/math.pi))*127+128))
p = PyAudio()
stream = p.open(format = p.get_format_from_width(1), 
            channels = 1, 
            rate = BITRATE, 
            output = True)
stream.write(WAVEDATA)

But I want a bit wider range than 0...255 which is the limitation of chr .

Any smart ideas?

I have tried:

WAVEDATA = WAVEDATA+struct.pack('f',math.sin(2*x/((BITRATE/FREQUENCY)/math.pi))) 

but it doesn't work, it plays just noise. I made a mistake somewhere.


Solution

  • OK, actually it was pretty simple (almost stupid). I've found two options:

    1. Here is good example how to do such thing: http://milkandtang.com/blog/2013/02/16/making-noise-in-python/

    2. Or just do this (with defined NUMBEROFFRAMES,BITRATE and FREQUENCY):

    import math
    import pyaudio
    import struct
    
    for x in xrange(NUMBEROFFRAMES):
        WAVEDATA = WAVEDATA+struct.pack('f',(math.sin(2*x/((BITRATE/FREQUENCY)/math.pi)))
    p = PyAudio()
    stream = p.open(format = p.get_format_from_width(4), 
            channels = 1, 
            rate = BITRATE, 
            output = True)
    stream.write(WAVEDATA)
    

    My stupid mistake was that I left 1 in get_format_from_width when I was working with floats. It should be 4.