PyAudio Input overflowed

后端 未结 9 1565
长发绾君心
长发绾君心 2020-11-30 04:04

I\'m trying to make real-time plotting sound in python. I need to get chunks from my microphone.

Using PyAudio, try to use

import pyaudio
import wav         


        
9条回答
  •  無奈伤痛
    2020-11-30 04:39

    For me this helped: https://stackoverflow.com/a/46787874/5047984

    I used multiprocessing to write the file in parallel to recording audio. This is my code:

    recordAudioSamples.py

    import pyaudio
    import wave
    import datetime
    import signal
    import ftplib
    import sys
    import os
    
    # configuration for assos_listen
    import config
    
    # run the audio capture and send sound sample processes
    # in parallel
    from multiprocessing import Process
    
    # CONFIG
    CHUNK = config.chunkSize
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = config.samplingRate
    RECORD_SECONDS = config.sampleLength
    
    # HELPER FUNCTIONS
    
    # write to ftp
    def uploadFile(filename):
    
        print("start uploading file: " + filename)
        # connect to container
        ftp = ftplib.FTP(config.ftp_server_ip, config.username, config.password)
    
        # write file
        ftp.storbinary('STOR '+filename, open(filename, 'rb'))
        # close connection
        ftp.quit()
        print("finished uploading: " +filename)
    
    # write to sd-card
    def storeFile(filename,frames):
    
        print("start writing file: " + filename)
        wf = wave.open(filename, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()
        print(filename + " written")
    
    # abort the sampling process
    def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')
    
        # close stream and pyAudio
        stream.stop_stream()
        stream.close()
        p.terminate()
    
        sys.exit(0)
    
    # MAIN FUNCTION
    def recordAudio(p, stream):
    
        sampleNumber = 0
        while (True):
            print("*  recording")
            sampleNumber = sampleNumber +1
    
            frames = []
            startDateTimeStr = datetime.datetime.now().strftime("%Y_%m_%d_%I_%M_%S_%f")
            for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                data = stream.read(CHUNK)
                frames.append(data)
    
            fileName =  str(config.sensorID) + "_" + startDateTimeStr + ".wav"
    
            # create a store process to write the file in parallel
            storeProcess = Process(target=storeFile, args=(fileName,frames))
            storeProcess.start()
    
            if (config.upload == True):
                # since waiting for the upload to finish will take some time
                # and we do not want to have gaps in our sample
                # we start the upload process in parallel
                print("start uploading...")
                uploadProcess = Process(target=uploadFile, args=(fileName,))
                uploadProcess.start()
    
    # ENTRYPOINT FROM CONSOLE
    if __name__ == '__main__':
    
        p = pyaudio.PyAudio()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)
    
        # directory to write and read files from
        os.chdir(config.storagePath)
    
        # abort by pressing C
        signal.signal(signal.SIGINT, signal_handler)
        print('\n\n--------------------------\npress Ctrl+C to stop the recording')
    
        # start recording
        recordAudio(p, stream)
    

    config.py

    ### configuration file for assos_listen
    # upload
    upload = False
    
    # config for this sensor
    sensorID = "al_01"
    
    # sampling rate & chunk size
    chunkSize = 8192
    samplingRate = 44100 # 44100 needed for Aves sampling
    # choices=[4000, 8000, 16000, 32000, 44100] :: default 16000
    
    # sample length in seconds
    sampleLength = 10
    
    # configuration for assos_store container
    ftp_server_ip = "192.168.0.157"
    username = "sensor"
    password = "sensor"
    
    # storage on assos_listen device
    storagePath = "/home/pi/assos_listen_pi/storage/"
    

提交回复
热议问题