
import os
import argparse
import threading
import pyaudio
import numpy as np

from queue import Queue


def processAudio(config, q):
	i = 0
	while True:
		try:
			data = q.get()
			i = i + 1
			print(data)

		except Exception as e:
			print("Ooopsi: ", e)

		q.task_done()


if __name__ == '__main__':

	# parser = argparse.ArgumentParser()
	# parser.add_argument('--input_file', type=str,
	# 					required=True,
	# 					help="path to the unbalanced_train_segments.csv")
	# parser.add_argument('--num_threads', type=int,
	# 					default=8,
	# 					help="amount of worker threads")
	# args = parser.parse_args()

	# worker queue
	queue = Queue()
	someConfig = ''

	worker = threading.Thread(target=processAudio, args=(someConfig, queue), daemon=True)
	worker.start()


	# Create an interface to PortAudio
	p = pyaudio.PyAudio()

	chunk = 1024  # Record in chunks of 1024 samples
	sample_format = pyaudio.paInt16  # 16 bits per sample
	channels = 2
	fs = 44100  # Record at 44100 samples per second
	seconds = 1
	filename = "output.wav"

	p = pyaudio.PyAudio()  # Create an interface to PortAudio

	stream = p.open(format=sample_format,
					channels=channels,
					rate=fs,
					frames_per_buffer=chunk,
					input=True)

	# record forever
	print('Recording')
	while True:
		data = stream.read(int(fs * seconds))
		queue.put(np.frombuffer(data, dtype=np.int16))

	# wait for thread to end
	queue.join()

	# Stop and close the stream 
	stream.stop_stream()
	stream.close()
	# Terminate the PortAudio interface
	p.terminate()

	# Close and terminate the stream
	stream.close()
	p.terminate()