Search code examples
python-3.xaudioreal-timepyaudio

Continuesly streaming audio signal real time infinitely, Python


I have a simple question, while streaming audio signal from audio jack in Python, using pyaudio library how can I keep streaming the audio signal until I choose to "stop" the program.

Example: The way we capture our web camera frames infinitely under a infinite while loop.

For example: In this code(take from link)that records the stream just for 5 seconds what will be the modification that will serve my purpose

import pyaudio
import wave
import numpy as np
CHUNK = 44100
FORMAT = pyaudio.paInt32
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording") 
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    audio_data = np.fromstring(data, dtype=np.int32)
    print(data)
    print(audio_data)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

Also the code given on this link (Handling audio data using callback mode) records it for 4-5 seconds.

I will be really grateful if someone could help me with this!!


Solution

  • Well , Meanwhile I figured out solution

    import pyaudio
    import numpy as np
    import pylab
    import time
    import sys
    import matplotlib.pyplot as plt
    
    
    RATE = 44100
    CHUNK = int(RATE/20) # RATE / number of updates per second
    
    def soundplot(stream):
      
       t1=time.time()
       #use np.frombuffer if you face error at this line
       data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
       print(data)
    
    if __name__=="__main__":
        p=pyaudio.PyAudio()
        stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
                      frames_per_buffer=CHUNK)
        for i in range(sys.maxsize**10):
            soundplot(stream)
        stream.stop_stream()
        stream.close()
        p.terminate()
    

    And this post here will help you in simple and concrete way