2015-01-20 106 views
1

你怎麼能設置一個變量等於「O」或「 - 」,然後把在類似下面的if語句:Pyaudio設置輸出=變量

if variable == 'O': 
    print 'hi' 

你怎麼能做到這一點的:

import threading 
from array import array 
from Queue import Queue, Full 
import pyaudio 


CHUNK_SIZE = 1024 
MIN_VOLUME = 500 
BUF_MAX_SIZE = CHUNK_SIZE * 10 


def main(): 
    stopped = threading.Event() 
    q = Queue(maxsize=int(round(BUF_MAX_SIZE/CHUNK_SIZE))) 

    listen_t = threading.Thread(target=listen, args=(stopped, q)) 
    listen_t.start() 
    record_t = threading.Thread(target=record, args=(stopped, q)) 
    record_t.start() 

    try: 
     while True: 
     listen_t.join(0.1) 
     record_t.join(0.1) 
    except KeyboardInterrupt: 
     stopped.set() 

    listen_t.join() 
    record_t.join() 


def record(stopped, q): 
    while True: 
     if stopped.wait(timeout=0): 
      break 
     chunk = q.get() 
     vol = max(chunk) 
     if vol >= MIN_VOLUME: 
     # TODO: write to file 
      print "O", 
     else: 
      print "-", 


def listen(stopped, q): 
    stream = pyaudio.PyAudio().open(
     format=pyaudio.paInt16, 
     channels=2, 
     rate=44100, 
     input=True, 
     frames_per_buffer=1024, 
    ) 

    while True: 
     if stopped.wait(timeout=0): 
      break 
     try: 
      q.put(array('h', stream.read(CHUNK_SIZE))) 
     except Full: 
      pass # discard 


if __name__ == '__main__': 
    main() 

您可以使用,因此,如果輸出是「O」然後打印喜?有人會爲我編寫代碼,因爲我一直在嘗試編寫這些代碼,但仍然無法使代碼適用於我。謝謝。

+0

你想把這些行放在哪裏? – Fahadkalis 2015-01-28 15:43:55

回答

1

爲了在Python中使用if語句,首先我們需要根據需求和類型用適當的語法聲明變量值。

s = "O" 
if s == 'O': 
    print 'hi' 
+0

請給你的回答添加一些解釋 – Huangism 2015-01-28 17:06:16

+0

@黃色其實這個問題很不清楚,我不知道他/她想把這些行放在哪裏 – Fahadkalis 2015-01-28 17:08:33

+0

可以理解的,你應該在發佈3行代碼之前先澄清一下,沒有任何解釋 – Huangism 2015-01-28 17:09:29