使用python从usb输入线程(麦克风)捕获一个音频样本

时间:2017-03-15 01:11:26

标签: python multithreading audio usb

目前,我正在启动我的主程序,该程序控制何时启动扬声器和麦克风线程。从那里我还可以控制设备上的静音/取消静音(USB耳机)等。音频线程位于音频类的单独文件中。

此代码有效。现在,它以预先设定的特定循环计数捕获音频样本。我希望从主程序请求时获取音频样本,但是我没有成功设置标志并在麦克风线程中检查它。我会得到pyaudio错误,如溢出/下溢。

如果有人建议采用技术来获取音频输入样本(麦克风数据),我将不胜感激。感谢

def openTheMic(self, **kwargs):
        # script can over-ride any value in the myAudio __init__
        print ("***in openTheMic ***")

        # picks up values passed by the test_script and maps them to myAudio class,
        # otherwise will use defaults set in class
        for (k,v) in kwargs.iteritems():
            #print("k = %s, v = %s" % (k,v))
            setattr(self, myAudio._map[k], v)

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

        setMicThreadStartTime(time.time())
        print("time @ start of mic thread is: %s" % time.time())
        starttime = time.time()
        while myAudio.openTheMicThreadActive == True:            
            for i in range(0, 1200):
                data = stream.read(self.CHUNK)
                captureCount = 1000

                if i == captureCount:
                    currentData = data
                    # abort the mic and spkr threads
                    myAudio.openTheMicThreadActive = False
                    myAudio.playDeadAirThreadActive = False
                    print("i is: %i: " % (i))
                    # set a global variable to get the data to the main program
                    setAudioData(currentData)
                    print("capture time: i = %s, time is %s " % (i, time.time()))


        stream.stop_stream()
        stream.close()
        print ("***closed the stream in openTheMic *** and the time is: %s" % time.time())
        self.p.terminate()

1 个答案:

答案 0 :(得分:0)

这种方法有效,但间歇性地出现上溢/下溢问题,但是一旦我将麦克风采样率设置为16kHz而不是默认值,这些问题就消失了。我稍微更改了代码,以便我可以随时从主程序中获取样本,使用全局标志var,mic循环检查它是否应该抓取样本。