Search code examples
pythonnumpystructpyaudiowave

Turning Audio into integers then back into Audio


import pyaudio
import struct 
import numpy as np
import wave

 #gather information from data
    n=(1024*4)
    sound = wave.open('test.wav','rb')
    num_sample = sound.getnframes()
    sample_rate = sound.getframerate()
    duration = round(num_sample/sample_rate, 4)

    #instantiate pyaudio and start stream
    p = pyaudio.PyAudio()

    stream = p.open(format = p.get_format_from_width(sound.getsampwidth()),
        channels = sound.getnchannels(),
        rate = sample_rate,
        output = True,
        frames_per_buffer = n)

    #Get data from .wav and turn it into integers
    data = sound.readframes(n)
    data_int = struct.unpack(str(len(data))+'B',data)
    print(data_int_test)

This is an part of my code where I have made a array of integers from the audio. I will try to add subtract multiply etc to the integers to see what happens. However, I don't know how to turn the integer array back into audio. I also tried to use numpy.frombuffer which also gave me integers but I was not quite sure how I might turn them back.If there is way with another module I'd be willing to do it that way. I'm sure numpy might have something.


Solution

  • Try to use write function from scipy.io.wavfile to .wav file.

    from scipy.io.wavfile import write
    
    write('test.wav', sample_rate, scaled)
    #write("filename.wav", int - sample rate, data)