PyAudio Input overflowedProducing spectrogram from microphoneUsing any other values in pyaudio for rate / format / chunk give me the error: [Errno Input overflowed] -9981IOError: [Errno Input overflowed] -9981Capture 192 kHz audio using Python 3PyAudio ErrNo Input Overflowed -9981Pyaudio: Error when wiring input to outputIOError Input overflowed: Record audio with Tkinter interfacepython2.7 on Raspberry Pi 3 - Pyaudio Input overflowedexception_on_overflow parameter not working? PyAudioPython Voice CommunicationPyAudio Memory ErrorPyAudio Over Network crashesPyAudio is clipping the end of soundPyaudio: Error when wiring input to outputReading soundcard output with pythonCan't record more than one wave with pyaudio (no default output device)Recording audio for specific amount of time with PyAudio?PyAudio and Audition CS6 recording different sample valueswhy Python input overflowed error in source code?

What happens if you are holding an Iron Flask with a demon inside and walk into an Antimagic Field?

Can a College of Swords bard use a Blade Flourish option on an opportunity attack provoked by their own Dissonant Whispers spell?

Mimic lecturing on blackboard, facing audience

Does IPv6 have similar concept of network mask?

How do you respond to a colleague from another team when they're wrongly expecting that you'll help them?

The IT department bottlenecks progress. How should I handle this?

Fear of getting stuck on one programming language / technology that is not used in my country

15% tax on $7.5k earnings. Is that right?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Strong empirical falsification of quantum mechanics based on vacuum energy density

Did arcade monitors have same pixel aspect ratio as TV sets?

Quoting Keynes in a lecture

Why can Carol Danvers change her suit colours in the first place?

Pre-mixing cryogenic fuels and using only one fuel tank

A social experiment. What is the worst that can happen?

Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?

Plot of a tornado-shaped surface

PTIJ: Haman's bad computer

Non-trope happy ending?

Why does the Sun have different day lengths, but not the gas giants?

How can "mimic phobia" be cured or prevented?

What is going on with 'gets(stdin)' on the site coderbyte?

Does Doodling or Improvising on the Piano Have Any Benefits?

What are some good ways to treat frozen vegetables such that they behave like fresh vegetables when stir frying them?



PyAudio Input overflowed


Producing spectrogram from microphoneUsing any other values in pyaudio for rate / format / chunk give me the error: [Errno Input overflowed] -9981IOError: [Errno Input overflowed] -9981Capture 192 kHz audio using Python 3PyAudio ErrNo Input Overflowed -9981Pyaudio: Error when wiring input to outputIOError Input overflowed: Record audio with Tkinter interfacepython2.7 on Raspberry Pi 3 - Pyaudio Input overflowedexception_on_overflow parameter not working? PyAudioPython Voice CommunicationPyAudio Memory ErrorPyAudio Over Network crashesPyAudio is clipping the end of soundPyaudio: Error when wiring input to outputReading soundcard output with pythonCan't record more than one wave with pyaudio (no default output device)Recording audio for specific amount of time with PyAudio?PyAudio and Audition CS6 recording different sample valueswhy Python input overflowed error in source code?













25















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 wave
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
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"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"

stream.close()
p.terminate()


After, I getting the followin error:



* recording
Traceback (most recent call last):
File "gg.py", line 23, in <module>
data = stream.read(chunk)
File "/usr/lib64/python2.7/site-packages/pyaudio.py", line 564, in read
return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981


I can't understand this buffer. I want, to use blocking IO mode, so if chunks not available, i want to wait for those chunks. But when I creating try except segment or sleep(0.1), i hear clicks, so this is not what i want.



Please suggest the best solution for my ploblem?










share|improve this question

















  • 2





    Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

    – Demolishun
    Nov 26 '12 at 14:06











  • Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

    – Jack Kelly
    Apr 10 '13 at 13:28
















25















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 wave
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
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"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"

stream.close()
p.terminate()


After, I getting the followin error:



* recording
Traceback (most recent call last):
File "gg.py", line 23, in <module>
data = stream.read(chunk)
File "/usr/lib64/python2.7/site-packages/pyaudio.py", line 564, in read
return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981


I can't understand this buffer. I want, to use blocking IO mode, so if chunks not available, i want to wait for those chunks. But when I creating try except segment or sleep(0.1), i hear clicks, so this is not what i want.



Please suggest the best solution for my ploblem?










share|improve this question

















  • 2





    Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

    – Demolishun
    Nov 26 '12 at 14:06











  • Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

    – Jack Kelly
    Apr 10 '13 at 13:28














25












25








25


6






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 wave
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
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"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"

stream.close()
p.terminate()


After, I getting the followin error:



* recording
Traceback (most recent call last):
File "gg.py", line 23, in <module>
data = stream.read(chunk)
File "/usr/lib64/python2.7/site-packages/pyaudio.py", line 564, in read
return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981


I can't understand this buffer. I want, to use blocking IO mode, so if chunks not available, i want to wait for those chunks. But when I creating try except segment or sleep(0.1), i hear clicks, so this is not what i want.



Please suggest the best solution for my ploblem?










share|improve this question














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 wave
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
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"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk)
all.append(data)
print "* done recording"

stream.close()
p.terminate()


After, I getting the followin error:



* recording
Traceback (most recent call last):
File "gg.py", line 23, in <module>
data = stream.read(chunk)
File "/usr/lib64/python2.7/site-packages/pyaudio.py", line 564, in read
return pa.read_stream(self._stream, num_frames)
IOError: [Errno Input overflowed] -9981


I can't understand this buffer. I want, to use blocking IO mode, so if chunks not available, i want to wait for those chunks. But when I creating try except segment or sleep(0.1), i hear clicks, so this is not what i want.



Please suggest the best solution for my ploblem?







python audio pyaudio






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 24 '12 at 8:36









libbkmzlibbkmz

1981316




1981316







  • 2





    Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

    – Demolishun
    Nov 26 '12 at 14:06











  • Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

    – Jack Kelly
    Apr 10 '13 at 13:28













  • 2





    Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

    – Demolishun
    Nov 26 '12 at 14:06











  • Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

    – Jack Kelly
    Apr 10 '13 at 13:28








2




2





Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

– Demolishun
Nov 26 '12 at 14:06





Perhaps your chunk size is too small. Maybe it is getting more data in the buffer than you are pulling out because the chunk size is small enough the Python code is not keeping up.

– Demolishun
Nov 26 '12 at 14:06













Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

– Jack Kelly
Apr 10 '13 at 13:28






Hi. Just wondering if there are any updates on this issue? I am getting the [Errno Input overflowed] -9981 error intermittently. I have checked p.is_format_supported is true for the format I am using.

– Jack Kelly
Apr 10 '13 at 13:28













9 Answers
9






active

oldest

votes


















15














pyaudio.Stream.read() has a keyword parameter exception_on_overflow, set this to False.



For your sample code that would look like:



import pyaudio
import wave
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
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"
all = []
for i in range(0, RATE / chunk * RECORD_SECONDS):
data = stream.read(chunk, exception_on_overflow = False)
all.append(data)
print "* done recording"

stream.close()
p.terminate()


See the PyAudio documentation for more details.






share|improve this answer


















  • 4





    I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

    – Nadav B
    Nov 8 '16 at 11:23


















9














I got the same error when I ran your code. I looked at the default sample rate of my default audio device, my macbook's internal microphone, it was 48000Hz not 44100Hz.



p.get_device_info_by_index(0)['defaultSampleRate']
Out[12]: 48000.0


When I changed RATE to this value, it worked.






share|improve this answer


















  • 1





    I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

    – user426364
    Feb 1 '13 at 16:28












  • Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

    – Joseph Sheedy
    Mar 27 '14 at 0:45











  • this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

    – Jeff
    Jul 17 '17 at 4:38











  • Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

    – Jason L.
    Feb 26 '18 at 18:18


















6














It seems like a lot of people are encountering this issue. I dug a bit into it and I think it means that between the previous call to stream.read() and this current call, data from the stream was lost (i.e. the buffer filled up faster than you cleared it).



From the doc for Pa_ReadStream() (the PortAudio function that stream.read() eventually ends up calling):



@return On success PaNoError will be returned, or PaInputOverflowed if
input data was discarded by PortAudio after the previous call and
before this call.


(PaInputOverflowed then causes an IOError in the pyaudio wrapper).



If it's OK for you to not capture every single frame, then you may ignore this error. If it's absolutely critical for you to have every frame, then you'll need to find a way to increase the priority of your application. I'm not familiar enough with Python to know a pythonic way to do this, but it's worth trying a simple nice command, or changing the scheduling policy to SCHED_DEADLINE.



Edit:



One issue right now is that when IOError is thrown, you lose all the frames collected in that call. To instead ignore the overflow and just return what we have, you can apply the patch below, which will cause stream.read() to ignore output underrun and input overflow errors from PortAudio (but still throw something if a different error occurred). A better way would be to make this behaviour (throw/no throw) customizable depending on your needs.



diff --git a/src/_portaudiomodule.c b/src/_portaudiomodule.c
index a8f053d..0878e74 100644
--- a/src/_portaudiomodule.c
+++ b/src/_portaudiomodule.c
@@ -2484,15 +2484,15 @@ pa_read_stream(PyObject *self, PyObject *args)
} else
/* clean up */
_cleanup_Stream_object(streamObject);
+
+ /* free the string buffer */
+ Py_XDECREF(rv);
+
+ PyErr_SetObject(PyExc_IOError,
+ Py_BuildValue("(s,i)",
+ Pa_GetErrorText(err), err));
+ return NULL;

-
- /* free the string buffer */
- Py_XDECREF(rv);
-
- PyErr_SetObject(PyExc_IOError,
- Py_BuildValue("(s,i)",
- Pa_GetErrorText(err), err));
- return NULL;
}

return rv;





share|improve this answer
































    3














    FORMAT = pyaudio.paInt16


    Make sure to set the correct format, my internal microphone was set to 24 Bit (see Audio-Midi-Setup application).






    share|improve this answer






























      3














      I worked this on OS X 10.10, Got the same error while trying to get audio from the microphone in a SYBA USB card (C Media chipset), and process it in real time with fft's and more:



      IOError: [Errno Input overflowed] -9981


      The overflow was completely solved when using a Callback Mode, instead of the Blocking Mode, as written by libbkmz.(https://www.python.org/dev/peps/pep-0263/)



      Based on that, the bit of the working code looked like this:



      """
      Creating the audio stream from our mic
      """
      rate=48000
      self.chunk=2**12
      width = 2

      p = pyaudio.PyAudio()

      # callback function to stream audio, another thread.
      def callback(in_data,frame_count, time_info, status):
      self.audio = numpy.fromstring(in_data,dtype=numpy.int16)
      return (self.audio, pyaudio.paContinue)

      #create a pyaudio object
      self.inStream = p.open(format = p.get_format_from_width(width, unsigned=False),
      channels=1,
      rate=rate,
      input=True,
      frames_per_buffer=self.chunk,
      stream_callback = callback)

      """
      Setting up the array that will handle the timeseries of audio data from our input
      """
      self.audio = numpy.empty((self.buffersize),dtype="int16")

      self.inStream.start_stream()

      while True:
      try:
      self.ANY_FUNCTION() #any function to run parallel to the audio thread, running forever, until ctrl+C is pressed.

      except KeyboardInterrupt:

      self.inStream.stop_stream()
      self.inStream.close()
      p.terminate()
      print("* Killed Process")
      quit()


      This code will create a callback function, then create a stream object, start it and then loop in any function. A separate thread streams audio, and that stream is closed when the main loop is stopped. self.audio is used in any function. I also had problems with the thread running forever if not terminated.



      Since Pyaudio runs this stream in a separate thread, and this made the audio stream stable, the Blocking mode might have been saturating depending on the speed or timing of the rest of the processes in the script.



      Note that the chunk size is 2^12, but smaller chunks work just as well. There are other parameters I considered and played around with to make sure they all made sense:



      • Chunk size larger or smaller(no effect)

      • Number and format of bits for the words in the buffer, signed 16 bit in this case.

      • signedness of variables(tried with unsigned and got saturation patterns)

      • Nature of mic input, and selection as default in the system, gain etc.

      Hope that works for someone!






      share|improve this answer
































        2














        My other answer solved the problem in most cases. However sometimes the error still occurs.



        That was the reason why I scrapped pyaudio and switched to pyalsaaudio. My Raspy now smoothly records any sound.



        import alsaaudio 
        import numpy as np
        import array

        # constants
        CHANNELS = 1
        INFORMAT = alsaaudio.PCM_FORMAT_FLOAT_LE
        RATE = 44100
        FRAMESIZE = 1024

        # set up audio input
        recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
        recorder.setchannels(CHANNELS)
        recorder.setrate(RATE)
        recorder.setformat(INFORMAT)
        recorder.setperiodsize(FRAMESIZE)


        buffer = array.array('f')
        while <some condition>:
        buffer.fromstring(recorder.read()[1])

        data = np.array(buffer, dtype='f')





        share|improve this answer
































          1














          I had the same issue on the really slow raspberry pi, but I was able to solve it (for most cases) by using the faster array module for storing the data.



          import array
          import pyaudio

          FORMAT = pyaudio.paInt16
          CHANNELS = 1
          INPUT_CHANNEL=2
          RATE = 48000
          CHUNK = 512

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

          print("* recording")


          try:
          data = array.array('h')
          for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
          data.fromstring(stream.read(CHUNK))
          finally:
          stream.stop_stream()
          stream.close()
          p.terminate()

          print("* done recording")


          The content of data is rather binary afterwards.
          But you can use numpy.array(data, dtype='i') to get a numpy array of intergers.






          share|improve this answer
































            0














            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('nn--------------------------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/"





            share|improve this answer






























              0














              This was helpful for me:



              input_ = stream.read(chunk, exception_on_overflow=False)
              exception_on_overflow = False





              share|improve this answer










              New contributor




              toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.



















                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10733903%2fpyaudio-input-overflowed%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                9 Answers
                9






                active

                oldest

                votes








                9 Answers
                9






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                15














                pyaudio.Stream.read() has a keyword parameter exception_on_overflow, set this to False.



                For your sample code that would look like:



                import pyaudio
                import wave
                import sys

                chunk = 1024
                FORMAT = pyaudio.paInt16
                CHANNELS = 1
                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"
                all = []
                for i in range(0, RATE / chunk * RECORD_SECONDS):
                data = stream.read(chunk, exception_on_overflow = False)
                all.append(data)
                print "* done recording"

                stream.close()
                p.terminate()


                See the PyAudio documentation for more details.






                share|improve this answer


















                • 4





                  I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                  – Nadav B
                  Nov 8 '16 at 11:23















                15














                pyaudio.Stream.read() has a keyword parameter exception_on_overflow, set this to False.



                For your sample code that would look like:



                import pyaudio
                import wave
                import sys

                chunk = 1024
                FORMAT = pyaudio.paInt16
                CHANNELS = 1
                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"
                all = []
                for i in range(0, RATE / chunk * RECORD_SECONDS):
                data = stream.read(chunk, exception_on_overflow = False)
                all.append(data)
                print "* done recording"

                stream.close()
                p.terminate()


                See the PyAudio documentation for more details.






                share|improve this answer


















                • 4





                  I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                  – Nadav B
                  Nov 8 '16 at 11:23













                15












                15








                15







                pyaudio.Stream.read() has a keyword parameter exception_on_overflow, set this to False.



                For your sample code that would look like:



                import pyaudio
                import wave
                import sys

                chunk = 1024
                FORMAT = pyaudio.paInt16
                CHANNELS = 1
                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"
                all = []
                for i in range(0, RATE / chunk * RECORD_SECONDS):
                data = stream.read(chunk, exception_on_overflow = False)
                all.append(data)
                print "* done recording"

                stream.close()
                p.terminate()


                See the PyAudio documentation for more details.






                share|improve this answer













                pyaudio.Stream.read() has a keyword parameter exception_on_overflow, set this to False.



                For your sample code that would look like:



                import pyaudio
                import wave
                import sys

                chunk = 1024
                FORMAT = pyaudio.paInt16
                CHANNELS = 1
                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"
                all = []
                for i in range(0, RATE / chunk * RECORD_SECONDS):
                data = stream.read(chunk, exception_on_overflow = False)
                all.append(data)
                print "* done recording"

                stream.close()
                p.terminate()


                See the PyAudio documentation for more details.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 16 '16 at 20:38









                JesquikJesquik

                15113




                15113







                • 4





                  I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                  – Nadav B
                  Nov 8 '16 at 11:23












                • 4





                  I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                  – Nadav B
                  Nov 8 '16 at 11:23







                4




                4





                I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                – Nadav B
                Nov 8 '16 at 11:23





                I get: TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

                – Nadav B
                Nov 8 '16 at 11:23













                9














                I got the same error when I ran your code. I looked at the default sample rate of my default audio device, my macbook's internal microphone, it was 48000Hz not 44100Hz.



                p.get_device_info_by_index(0)['defaultSampleRate']
                Out[12]: 48000.0


                When I changed RATE to this value, it worked.






                share|improve this answer


















                • 1





                  I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                  – user426364
                  Feb 1 '13 at 16:28












                • Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                  – Joseph Sheedy
                  Mar 27 '14 at 0:45











                • this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                  – Jeff
                  Jul 17 '17 at 4:38











                • Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                  – Jason L.
                  Feb 26 '18 at 18:18















                9














                I got the same error when I ran your code. I looked at the default sample rate of my default audio device, my macbook's internal microphone, it was 48000Hz not 44100Hz.



                p.get_device_info_by_index(0)['defaultSampleRate']
                Out[12]: 48000.0


                When I changed RATE to this value, it worked.






                share|improve this answer


















                • 1





                  I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                  – user426364
                  Feb 1 '13 at 16:28












                • Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                  – Joseph Sheedy
                  Mar 27 '14 at 0:45











                • this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                  – Jeff
                  Jul 17 '17 at 4:38











                • Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                  – Jason L.
                  Feb 26 '18 at 18:18













                9












                9








                9







                I got the same error when I ran your code. I looked at the default sample rate of my default audio device, my macbook's internal microphone, it was 48000Hz not 44100Hz.



                p.get_device_info_by_index(0)['defaultSampleRate']
                Out[12]: 48000.0


                When I changed RATE to this value, it worked.






                share|improve this answer













                I got the same error when I ran your code. I looked at the default sample rate of my default audio device, my macbook's internal microphone, it was 48000Hz not 44100Hz.



                p.get_device_info_by_index(0)['defaultSampleRate']
                Out[12]: 48000.0


                When I changed RATE to this value, it worked.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 8 '12 at 5:10









                Joseph SheedyJoseph Sheedy

                3,68121726




                3,68121726







                • 1





                  I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                  – user426364
                  Feb 1 '13 at 16:28












                • Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                  – Joseph Sheedy
                  Mar 27 '14 at 0:45











                • this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                  – Jeff
                  Jul 17 '17 at 4:38











                • Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                  – Jason L.
                  Feb 26 '18 at 18:18












                • 1





                  I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                  – user426364
                  Feb 1 '13 at 16:28












                • Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                  – Joseph Sheedy
                  Mar 27 '14 at 0:45











                • this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                  – Jeff
                  Jul 17 '17 at 4:38











                • Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                  – Jason L.
                  Feb 26 '18 at 18:18







                1




                1





                I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                – user426364
                Feb 1 '13 at 16:28






                I got the same error, and your solution (upping to 48000) worked. But I had run the code: if p.is_format_supported(44100.0, # Sample rate input_device=devinfo["index"], input_channels=devinfo['maxInputChannels'], input_format=pyaudio.paInt16): print 'Yay!' ... and it worked! So I am confused as to what the problem was. Any insight?

                – user426364
                Feb 1 '13 at 16:28














                Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                – Joseph Sheedy
                Mar 27 '14 at 0:45





                Try upgrading portaudio, this fixed some rate problems for me. I used "brew install portaudio --HEAD".

                – Joseph Sheedy
                Mar 27 '14 at 0:45













                this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                – Jeff
                Jul 17 '17 at 4:38





                this worked for me, I did not realize soundcard's default sampling rate was 48khz, thanks!

                – Jeff
                Jul 17 '17 at 4:38













                Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                – Jason L.
                Feb 26 '18 at 18:18





                Thanks, this was my issue, too. I would not have expected this to be a problem on budget hardware but maybe 48k is becoming the de-facto norm?

                – Jason L.
                Feb 26 '18 at 18:18











                6














                It seems like a lot of people are encountering this issue. I dug a bit into it and I think it means that between the previous call to stream.read() and this current call, data from the stream was lost (i.e. the buffer filled up faster than you cleared it).



                From the doc for Pa_ReadStream() (the PortAudio function that stream.read() eventually ends up calling):



                @return On success PaNoError will be returned, or PaInputOverflowed if
                input data was discarded by PortAudio after the previous call and
                before this call.


                (PaInputOverflowed then causes an IOError in the pyaudio wrapper).



                If it's OK for you to not capture every single frame, then you may ignore this error. If it's absolutely critical for you to have every frame, then you'll need to find a way to increase the priority of your application. I'm not familiar enough with Python to know a pythonic way to do this, but it's worth trying a simple nice command, or changing the scheduling policy to SCHED_DEADLINE.



                Edit:



                One issue right now is that when IOError is thrown, you lose all the frames collected in that call. To instead ignore the overflow and just return what we have, you can apply the patch below, which will cause stream.read() to ignore output underrun and input overflow errors from PortAudio (but still throw something if a different error occurred). A better way would be to make this behaviour (throw/no throw) customizable depending on your needs.



                diff --git a/src/_portaudiomodule.c b/src/_portaudiomodule.c
                index a8f053d..0878e74 100644
                --- a/src/_portaudiomodule.c
                +++ b/src/_portaudiomodule.c
                @@ -2484,15 +2484,15 @@ pa_read_stream(PyObject *self, PyObject *args)
                } else
                /* clean up */
                _cleanup_Stream_object(streamObject);
                +
                + /* free the string buffer */
                + Py_XDECREF(rv);
                +
                + PyErr_SetObject(PyExc_IOError,
                + Py_BuildValue("(s,i)",
                + Pa_GetErrorText(err), err));
                + return NULL;

                -
                - /* free the string buffer */
                - Py_XDECREF(rv);
                -
                - PyErr_SetObject(PyExc_IOError,
                - Py_BuildValue("(s,i)",
                - Pa_GetErrorText(err), err));
                - return NULL;
                }

                return rv;





                share|improve this answer





























                  6














                  It seems like a lot of people are encountering this issue. I dug a bit into it and I think it means that between the previous call to stream.read() and this current call, data from the stream was lost (i.e. the buffer filled up faster than you cleared it).



                  From the doc for Pa_ReadStream() (the PortAudio function that stream.read() eventually ends up calling):



                  @return On success PaNoError will be returned, or PaInputOverflowed if
                  input data was discarded by PortAudio after the previous call and
                  before this call.


                  (PaInputOverflowed then causes an IOError in the pyaudio wrapper).



                  If it's OK for you to not capture every single frame, then you may ignore this error. If it's absolutely critical for you to have every frame, then you'll need to find a way to increase the priority of your application. I'm not familiar enough with Python to know a pythonic way to do this, but it's worth trying a simple nice command, or changing the scheduling policy to SCHED_DEADLINE.



                  Edit:



                  One issue right now is that when IOError is thrown, you lose all the frames collected in that call. To instead ignore the overflow and just return what we have, you can apply the patch below, which will cause stream.read() to ignore output underrun and input overflow errors from PortAudio (but still throw something if a different error occurred). A better way would be to make this behaviour (throw/no throw) customizable depending on your needs.



                  diff --git a/src/_portaudiomodule.c b/src/_portaudiomodule.c
                  index a8f053d..0878e74 100644
                  --- a/src/_portaudiomodule.c
                  +++ b/src/_portaudiomodule.c
                  @@ -2484,15 +2484,15 @@ pa_read_stream(PyObject *self, PyObject *args)
                  } else
                  /* clean up */
                  _cleanup_Stream_object(streamObject);
                  +
                  + /* free the string buffer */
                  + Py_XDECREF(rv);
                  +
                  + PyErr_SetObject(PyExc_IOError,
                  + Py_BuildValue("(s,i)",
                  + Pa_GetErrorText(err), err));
                  + return NULL;

                  -
                  - /* free the string buffer */
                  - Py_XDECREF(rv);
                  -
                  - PyErr_SetObject(PyExc_IOError,
                  - Py_BuildValue("(s,i)",
                  - Pa_GetErrorText(err), err));
                  - return NULL;
                  }

                  return rv;





                  share|improve this answer



























                    6












                    6








                    6







                    It seems like a lot of people are encountering this issue. I dug a bit into it and I think it means that between the previous call to stream.read() and this current call, data from the stream was lost (i.e. the buffer filled up faster than you cleared it).



                    From the doc for Pa_ReadStream() (the PortAudio function that stream.read() eventually ends up calling):



                    @return On success PaNoError will be returned, or PaInputOverflowed if
                    input data was discarded by PortAudio after the previous call and
                    before this call.


                    (PaInputOverflowed then causes an IOError in the pyaudio wrapper).



                    If it's OK for you to not capture every single frame, then you may ignore this error. If it's absolutely critical for you to have every frame, then you'll need to find a way to increase the priority of your application. I'm not familiar enough with Python to know a pythonic way to do this, but it's worth trying a simple nice command, or changing the scheduling policy to SCHED_DEADLINE.



                    Edit:



                    One issue right now is that when IOError is thrown, you lose all the frames collected in that call. To instead ignore the overflow and just return what we have, you can apply the patch below, which will cause stream.read() to ignore output underrun and input overflow errors from PortAudio (but still throw something if a different error occurred). A better way would be to make this behaviour (throw/no throw) customizable depending on your needs.



                    diff --git a/src/_portaudiomodule.c b/src/_portaudiomodule.c
                    index a8f053d..0878e74 100644
                    --- a/src/_portaudiomodule.c
                    +++ b/src/_portaudiomodule.c
                    @@ -2484,15 +2484,15 @@ pa_read_stream(PyObject *self, PyObject *args)
                    } else
                    /* clean up */
                    _cleanup_Stream_object(streamObject);
                    +
                    + /* free the string buffer */
                    + Py_XDECREF(rv);
                    +
                    + PyErr_SetObject(PyExc_IOError,
                    + Py_BuildValue("(s,i)",
                    + Pa_GetErrorText(err), err));
                    + return NULL;

                    -
                    - /* free the string buffer */
                    - Py_XDECREF(rv);
                    -
                    - PyErr_SetObject(PyExc_IOError,
                    - Py_BuildValue("(s,i)",
                    - Pa_GetErrorText(err), err));
                    - return NULL;
                    }

                    return rv;





                    share|improve this answer















                    It seems like a lot of people are encountering this issue. I dug a bit into it and I think it means that between the previous call to stream.read() and this current call, data from the stream was lost (i.e. the buffer filled up faster than you cleared it).



                    From the doc for Pa_ReadStream() (the PortAudio function that stream.read() eventually ends up calling):



                    @return On success PaNoError will be returned, or PaInputOverflowed if
                    input data was discarded by PortAudio after the previous call and
                    before this call.


                    (PaInputOverflowed then causes an IOError in the pyaudio wrapper).



                    If it's OK for you to not capture every single frame, then you may ignore this error. If it's absolutely critical for you to have every frame, then you'll need to find a way to increase the priority of your application. I'm not familiar enough with Python to know a pythonic way to do this, but it's worth trying a simple nice command, or changing the scheduling policy to SCHED_DEADLINE.



                    Edit:



                    One issue right now is that when IOError is thrown, you lose all the frames collected in that call. To instead ignore the overflow and just return what we have, you can apply the patch below, which will cause stream.read() to ignore output underrun and input overflow errors from PortAudio (but still throw something if a different error occurred). A better way would be to make this behaviour (throw/no throw) customizable depending on your needs.



                    diff --git a/src/_portaudiomodule.c b/src/_portaudiomodule.c
                    index a8f053d..0878e74 100644
                    --- a/src/_portaudiomodule.c
                    +++ b/src/_portaudiomodule.c
                    @@ -2484,15 +2484,15 @@ pa_read_stream(PyObject *self, PyObject *args)
                    } else
                    /* clean up */
                    _cleanup_Stream_object(streamObject);
                    +
                    + /* free the string buffer */
                    + Py_XDECREF(rv);
                    +
                    + PyErr_SetObject(PyExc_IOError,
                    + Py_BuildValue("(s,i)",
                    + Pa_GetErrorText(err), err));
                    + return NULL;

                    -
                    - /* free the string buffer */
                    - Py_XDECREF(rv);
                    -
                    - PyErr_SetObject(PyExc_IOError,
                    - Py_BuildValue("(s,i)",
                    - Pa_GetErrorText(err), err));
                    - return NULL;
                    }

                    return rv;






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 18 '15 at 15:23

























                    answered Feb 18 '15 at 1:41









                    MetaMeta

                    75321226




                    75321226





















                        3














                        FORMAT = pyaudio.paInt16


                        Make sure to set the correct format, my internal microphone was set to 24 Bit (see Audio-Midi-Setup application).






                        share|improve this answer



























                          3














                          FORMAT = pyaudio.paInt16


                          Make sure to set the correct format, my internal microphone was set to 24 Bit (see Audio-Midi-Setup application).






                          share|improve this answer

























                            3












                            3








                            3







                            FORMAT = pyaudio.paInt16


                            Make sure to set the correct format, my internal microphone was set to 24 Bit (see Audio-Midi-Setup application).






                            share|improve this answer













                            FORMAT = pyaudio.paInt16


                            Make sure to set the correct format, my internal microphone was set to 24 Bit (see Audio-Midi-Setup application).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 15 '13 at 15:48









                            w-mw-m

                            6,3342434




                            6,3342434





















                                3














                                I worked this on OS X 10.10, Got the same error while trying to get audio from the microphone in a SYBA USB card (C Media chipset), and process it in real time with fft's and more:



                                IOError: [Errno Input overflowed] -9981


                                The overflow was completely solved when using a Callback Mode, instead of the Blocking Mode, as written by libbkmz.(https://www.python.org/dev/peps/pep-0263/)



                                Based on that, the bit of the working code looked like this:



                                """
                                Creating the audio stream from our mic
                                """
                                rate=48000
                                self.chunk=2**12
                                width = 2

                                p = pyaudio.PyAudio()

                                # callback function to stream audio, another thread.
                                def callback(in_data,frame_count, time_info, status):
                                self.audio = numpy.fromstring(in_data,dtype=numpy.int16)
                                return (self.audio, pyaudio.paContinue)

                                #create a pyaudio object
                                self.inStream = p.open(format = p.get_format_from_width(width, unsigned=False),
                                channels=1,
                                rate=rate,
                                input=True,
                                frames_per_buffer=self.chunk,
                                stream_callback = callback)

                                """
                                Setting up the array that will handle the timeseries of audio data from our input
                                """
                                self.audio = numpy.empty((self.buffersize),dtype="int16")

                                self.inStream.start_stream()

                                while True:
                                try:
                                self.ANY_FUNCTION() #any function to run parallel to the audio thread, running forever, until ctrl+C is pressed.

                                except KeyboardInterrupt:

                                self.inStream.stop_stream()
                                self.inStream.close()
                                p.terminate()
                                print("* Killed Process")
                                quit()


                                This code will create a callback function, then create a stream object, start it and then loop in any function. A separate thread streams audio, and that stream is closed when the main loop is stopped. self.audio is used in any function. I also had problems with the thread running forever if not terminated.



                                Since Pyaudio runs this stream in a separate thread, and this made the audio stream stable, the Blocking mode might have been saturating depending on the speed or timing of the rest of the processes in the script.



                                Note that the chunk size is 2^12, but smaller chunks work just as well. There are other parameters I considered and played around with to make sure they all made sense:



                                • Chunk size larger or smaller(no effect)

                                • Number and format of bits for the words in the buffer, signed 16 bit in this case.

                                • signedness of variables(tried with unsigned and got saturation patterns)

                                • Nature of mic input, and selection as default in the system, gain etc.

                                Hope that works for someone!






                                share|improve this answer





























                                  3














                                  I worked this on OS X 10.10, Got the same error while trying to get audio from the microphone in a SYBA USB card (C Media chipset), and process it in real time with fft's and more:



                                  IOError: [Errno Input overflowed] -9981


                                  The overflow was completely solved when using a Callback Mode, instead of the Blocking Mode, as written by libbkmz.(https://www.python.org/dev/peps/pep-0263/)



                                  Based on that, the bit of the working code looked like this:



                                  """
                                  Creating the audio stream from our mic
                                  """
                                  rate=48000
                                  self.chunk=2**12
                                  width = 2

                                  p = pyaudio.PyAudio()

                                  # callback function to stream audio, another thread.
                                  def callback(in_data,frame_count, time_info, status):
                                  self.audio = numpy.fromstring(in_data,dtype=numpy.int16)
                                  return (self.audio, pyaudio.paContinue)

                                  #create a pyaudio object
                                  self.inStream = p.open(format = p.get_format_from_width(width, unsigned=False),
                                  channels=1,
                                  rate=rate,
                                  input=True,
                                  frames_per_buffer=self.chunk,
                                  stream_callback = callback)

                                  """
                                  Setting up the array that will handle the timeseries of audio data from our input
                                  """
                                  self.audio = numpy.empty((self.buffersize),dtype="int16")

                                  self.inStream.start_stream()

                                  while True:
                                  try:
                                  self.ANY_FUNCTION() #any function to run parallel to the audio thread, running forever, until ctrl+C is pressed.

                                  except KeyboardInterrupt:

                                  self.inStream.stop_stream()
                                  self.inStream.close()
                                  p.terminate()
                                  print("* Killed Process")
                                  quit()


                                  This code will create a callback function, then create a stream object, start it and then loop in any function. A separate thread streams audio, and that stream is closed when the main loop is stopped. self.audio is used in any function. I also had problems with the thread running forever if not terminated.



                                  Since Pyaudio runs this stream in a separate thread, and this made the audio stream stable, the Blocking mode might have been saturating depending on the speed or timing of the rest of the processes in the script.



                                  Note that the chunk size is 2^12, but smaller chunks work just as well. There are other parameters I considered and played around with to make sure they all made sense:



                                  • Chunk size larger or smaller(no effect)

                                  • Number and format of bits for the words in the buffer, signed 16 bit in this case.

                                  • signedness of variables(tried with unsigned and got saturation patterns)

                                  • Nature of mic input, and selection as default in the system, gain etc.

                                  Hope that works for someone!






                                  share|improve this answer



























                                    3












                                    3








                                    3







                                    I worked this on OS X 10.10, Got the same error while trying to get audio from the microphone in a SYBA USB card (C Media chipset), and process it in real time with fft's and more:



                                    IOError: [Errno Input overflowed] -9981


                                    The overflow was completely solved when using a Callback Mode, instead of the Blocking Mode, as written by libbkmz.(https://www.python.org/dev/peps/pep-0263/)



                                    Based on that, the bit of the working code looked like this:



                                    """
                                    Creating the audio stream from our mic
                                    """
                                    rate=48000
                                    self.chunk=2**12
                                    width = 2

                                    p = pyaudio.PyAudio()

                                    # callback function to stream audio, another thread.
                                    def callback(in_data,frame_count, time_info, status):
                                    self.audio = numpy.fromstring(in_data,dtype=numpy.int16)
                                    return (self.audio, pyaudio.paContinue)

                                    #create a pyaudio object
                                    self.inStream = p.open(format = p.get_format_from_width(width, unsigned=False),
                                    channels=1,
                                    rate=rate,
                                    input=True,
                                    frames_per_buffer=self.chunk,
                                    stream_callback = callback)

                                    """
                                    Setting up the array that will handle the timeseries of audio data from our input
                                    """
                                    self.audio = numpy.empty((self.buffersize),dtype="int16")

                                    self.inStream.start_stream()

                                    while True:
                                    try:
                                    self.ANY_FUNCTION() #any function to run parallel to the audio thread, running forever, until ctrl+C is pressed.

                                    except KeyboardInterrupt:

                                    self.inStream.stop_stream()
                                    self.inStream.close()
                                    p.terminate()
                                    print("* Killed Process")
                                    quit()


                                    This code will create a callback function, then create a stream object, start it and then loop in any function. A separate thread streams audio, and that stream is closed when the main loop is stopped. self.audio is used in any function. I also had problems with the thread running forever if not terminated.



                                    Since Pyaudio runs this stream in a separate thread, and this made the audio stream stable, the Blocking mode might have been saturating depending on the speed or timing of the rest of the processes in the script.



                                    Note that the chunk size is 2^12, but smaller chunks work just as well. There are other parameters I considered and played around with to make sure they all made sense:



                                    • Chunk size larger or smaller(no effect)

                                    • Number and format of bits for the words in the buffer, signed 16 bit in this case.

                                    • signedness of variables(tried with unsigned and got saturation patterns)

                                    • Nature of mic input, and selection as default in the system, gain etc.

                                    Hope that works for someone!






                                    share|improve this answer















                                    I worked this on OS X 10.10, Got the same error while trying to get audio from the microphone in a SYBA USB card (C Media chipset), and process it in real time with fft's and more:



                                    IOError: [Errno Input overflowed] -9981


                                    The overflow was completely solved when using a Callback Mode, instead of the Blocking Mode, as written by libbkmz.(https://www.python.org/dev/peps/pep-0263/)



                                    Based on that, the bit of the working code looked like this:



                                    """
                                    Creating the audio stream from our mic
                                    """
                                    rate=48000
                                    self.chunk=2**12
                                    width = 2

                                    p = pyaudio.PyAudio()

                                    # callback function to stream audio, another thread.
                                    def callback(in_data,frame_count, time_info, status):
                                    self.audio = numpy.fromstring(in_data,dtype=numpy.int16)
                                    return (self.audio, pyaudio.paContinue)

                                    #create a pyaudio object
                                    self.inStream = p.open(format = p.get_format_from_width(width, unsigned=False),
                                    channels=1,
                                    rate=rate,
                                    input=True,
                                    frames_per_buffer=self.chunk,
                                    stream_callback = callback)

                                    """
                                    Setting up the array that will handle the timeseries of audio data from our input
                                    """
                                    self.audio = numpy.empty((self.buffersize),dtype="int16")

                                    self.inStream.start_stream()

                                    while True:
                                    try:
                                    self.ANY_FUNCTION() #any function to run parallel to the audio thread, running forever, until ctrl+C is pressed.

                                    except KeyboardInterrupt:

                                    self.inStream.stop_stream()
                                    self.inStream.close()
                                    p.terminate()
                                    print("* Killed Process")
                                    quit()


                                    This code will create a callback function, then create a stream object, start it and then loop in any function. A separate thread streams audio, and that stream is closed when the main loop is stopped. self.audio is used in any function. I also had problems with the thread running forever if not terminated.



                                    Since Pyaudio runs this stream in a separate thread, and this made the audio stream stable, the Blocking mode might have been saturating depending on the speed or timing of the rest of the processes in the script.



                                    Note that the chunk size is 2^12, but smaller chunks work just as well. There are other parameters I considered and played around with to make sure they all made sense:



                                    • Chunk size larger or smaller(no effect)

                                    • Number and format of bits for the words in the buffer, signed 16 bit in this case.

                                    • signedness of variables(tried with unsigned and got saturation patterns)

                                    • Nature of mic input, and selection as default in the system, gain etc.

                                    Hope that works for someone!







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Oct 2 '15 at 6:24

























                                    answered Oct 2 '15 at 5:59









                                    Roberto BecerraRoberto Becerra

                                    516




                                    516





















                                        2














                                        My other answer solved the problem in most cases. However sometimes the error still occurs.



                                        That was the reason why I scrapped pyaudio and switched to pyalsaaudio. My Raspy now smoothly records any sound.



                                        import alsaaudio 
                                        import numpy as np
                                        import array

                                        # constants
                                        CHANNELS = 1
                                        INFORMAT = alsaaudio.PCM_FORMAT_FLOAT_LE
                                        RATE = 44100
                                        FRAMESIZE = 1024

                                        # set up audio input
                                        recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
                                        recorder.setchannels(CHANNELS)
                                        recorder.setrate(RATE)
                                        recorder.setformat(INFORMAT)
                                        recorder.setperiodsize(FRAMESIZE)


                                        buffer = array.array('f')
                                        while <some condition>:
                                        buffer.fromstring(recorder.read()[1])

                                        data = np.array(buffer, dtype='f')





                                        share|improve this answer





























                                          2














                                          My other answer solved the problem in most cases. However sometimes the error still occurs.



                                          That was the reason why I scrapped pyaudio and switched to pyalsaaudio. My Raspy now smoothly records any sound.



                                          import alsaaudio 
                                          import numpy as np
                                          import array

                                          # constants
                                          CHANNELS = 1
                                          INFORMAT = alsaaudio.PCM_FORMAT_FLOAT_LE
                                          RATE = 44100
                                          FRAMESIZE = 1024

                                          # set up audio input
                                          recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
                                          recorder.setchannels(CHANNELS)
                                          recorder.setrate(RATE)
                                          recorder.setformat(INFORMAT)
                                          recorder.setperiodsize(FRAMESIZE)


                                          buffer = array.array('f')
                                          while <some condition>:
                                          buffer.fromstring(recorder.read()[1])

                                          data = np.array(buffer, dtype='f')





                                          share|improve this answer



























                                            2












                                            2








                                            2







                                            My other answer solved the problem in most cases. However sometimes the error still occurs.



                                            That was the reason why I scrapped pyaudio and switched to pyalsaaudio. My Raspy now smoothly records any sound.



                                            import alsaaudio 
                                            import numpy as np
                                            import array

                                            # constants
                                            CHANNELS = 1
                                            INFORMAT = alsaaudio.PCM_FORMAT_FLOAT_LE
                                            RATE = 44100
                                            FRAMESIZE = 1024

                                            # set up audio input
                                            recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
                                            recorder.setchannels(CHANNELS)
                                            recorder.setrate(RATE)
                                            recorder.setformat(INFORMAT)
                                            recorder.setperiodsize(FRAMESIZE)


                                            buffer = array.array('f')
                                            while <some condition>:
                                            buffer.fromstring(recorder.read()[1])

                                            data = np.array(buffer, dtype='f')





                                            share|improve this answer















                                            My other answer solved the problem in most cases. However sometimes the error still occurs.



                                            That was the reason why I scrapped pyaudio and switched to pyalsaaudio. My Raspy now smoothly records any sound.



                                            import alsaaudio 
                                            import numpy as np
                                            import array

                                            # constants
                                            CHANNELS = 1
                                            INFORMAT = alsaaudio.PCM_FORMAT_FLOAT_LE
                                            RATE = 44100
                                            FRAMESIZE = 1024

                                            # set up audio input
                                            recorder=alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
                                            recorder.setchannels(CHANNELS)
                                            recorder.setrate(RATE)
                                            recorder.setformat(INFORMAT)
                                            recorder.setperiodsize(FRAMESIZE)


                                            buffer = array.array('f')
                                            while <some condition>:
                                            buffer.fromstring(recorder.read()[1])

                                            data = np.array(buffer, dtype='f')






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jan 14 '16 at 18:23

























                                            answered Jan 14 '16 at 18:13









                                            Harald ThomsonHarald Thomson

                                            2291211




                                            2291211





















                                                1














                                                I had the same issue on the really slow raspberry pi, but I was able to solve it (for most cases) by using the faster array module for storing the data.



                                                import array
                                                import pyaudio

                                                FORMAT = pyaudio.paInt16
                                                CHANNELS = 1
                                                INPUT_CHANNEL=2
                                                RATE = 48000
                                                CHUNK = 512

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

                                                print("* recording")


                                                try:
                                                data = array.array('h')
                                                for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                                                data.fromstring(stream.read(CHUNK))
                                                finally:
                                                stream.stop_stream()
                                                stream.close()
                                                p.terminate()

                                                print("* done recording")


                                                The content of data is rather binary afterwards.
                                                But you can use numpy.array(data, dtype='i') to get a numpy array of intergers.






                                                share|improve this answer





























                                                  1














                                                  I had the same issue on the really slow raspberry pi, but I was able to solve it (for most cases) by using the faster array module for storing the data.



                                                  import array
                                                  import pyaudio

                                                  FORMAT = pyaudio.paInt16
                                                  CHANNELS = 1
                                                  INPUT_CHANNEL=2
                                                  RATE = 48000
                                                  CHUNK = 512

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

                                                  print("* recording")


                                                  try:
                                                  data = array.array('h')
                                                  for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                                                  data.fromstring(stream.read(CHUNK))
                                                  finally:
                                                  stream.stop_stream()
                                                  stream.close()
                                                  p.terminate()

                                                  print("* done recording")


                                                  The content of data is rather binary afterwards.
                                                  But you can use numpy.array(data, dtype='i') to get a numpy array of intergers.






                                                  share|improve this answer



























                                                    1












                                                    1








                                                    1







                                                    I had the same issue on the really slow raspberry pi, but I was able to solve it (for most cases) by using the faster array module for storing the data.



                                                    import array
                                                    import pyaudio

                                                    FORMAT = pyaudio.paInt16
                                                    CHANNELS = 1
                                                    INPUT_CHANNEL=2
                                                    RATE = 48000
                                                    CHUNK = 512

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

                                                    print("* recording")


                                                    try:
                                                    data = array.array('h')
                                                    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                                                    data.fromstring(stream.read(CHUNK))
                                                    finally:
                                                    stream.stop_stream()
                                                    stream.close()
                                                    p.terminate()

                                                    print("* done recording")


                                                    The content of data is rather binary afterwards.
                                                    But you can use numpy.array(data, dtype='i') to get a numpy array of intergers.






                                                    share|improve this answer















                                                    I had the same issue on the really slow raspberry pi, but I was able to solve it (for most cases) by using the faster array module for storing the data.



                                                    import array
                                                    import pyaudio

                                                    FORMAT = pyaudio.paInt16
                                                    CHANNELS = 1
                                                    INPUT_CHANNEL=2
                                                    RATE = 48000
                                                    CHUNK = 512

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

                                                    print("* recording")


                                                    try:
                                                    data = array.array('h')
                                                    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                                                    data.fromstring(stream.read(CHUNK))
                                                    finally:
                                                    stream.stop_stream()
                                                    stream.close()
                                                    p.terminate()

                                                    print("* done recording")


                                                    The content of data is rather binary afterwards.
                                                    But you can use numpy.array(data, dtype='i') to get a numpy array of intergers.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Jan 14 '16 at 18:27

























                                                    answered Jan 14 '16 at 12:13









                                                    Harald ThomsonHarald Thomson

                                                    2291211




                                                    2291211





















                                                        0














                                                        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('nn--------------------------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/"





                                                        share|improve this answer



























                                                          0














                                                          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('nn--------------------------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/"





                                                          share|improve this answer

























                                                            0












                                                            0








                                                            0







                                                            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('nn--------------------------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/"





                                                            share|improve this answer













                                                            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('nn--------------------------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/"






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Oct 17 '17 at 10:38









                                                            gannebammgannebamm

                                                            11




                                                            11





















                                                                0














                                                                This was helpful for me:



                                                                input_ = stream.read(chunk, exception_on_overflow=False)
                                                                exception_on_overflow = False





                                                                share|improve this answer










                                                                New contributor




                                                                toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                Check out our Code of Conduct.
























                                                                  0














                                                                  This was helpful for me:



                                                                  input_ = stream.read(chunk, exception_on_overflow=False)
                                                                  exception_on_overflow = False





                                                                  share|improve this answer










                                                                  New contributor




                                                                  toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                  Check out our Code of Conduct.






















                                                                    0












                                                                    0








                                                                    0







                                                                    This was helpful for me:



                                                                    input_ = stream.read(chunk, exception_on_overflow=False)
                                                                    exception_on_overflow = False





                                                                    share|improve this answer










                                                                    New contributor




                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.










                                                                    This was helpful for me:



                                                                    input_ = stream.read(chunk, exception_on_overflow=False)
                                                                    exception_on_overflow = False






                                                                    share|improve this answer










                                                                    New contributor




                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.









                                                                    share|improve this answer



                                                                    share|improve this answer








                                                                    edited yesterday









                                                                    Nino Filiu

                                                                    2,17131228




                                                                    2,17131228






                                                                    New contributor




                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.









                                                                    answered yesterday









                                                                    toborobottoborobot

                                                                    1




                                                                    1




                                                                    New contributor




                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.





                                                                    New contributor





                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.






                                                                    toborobot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                                                    Check out our Code of Conduct.



























                                                                        draft saved

                                                                        draft discarded
















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid


                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.

                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function ()
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10733903%2fpyaudio-input-overflowed%23new-answer', 'question_page');

                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                        Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                                        Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript