from socket import *
from audio.audioserver import AudioServer
from audio.sink.alsasink import AlsaSink
import os
import signal
from asyncproc import Process
from threading import Thread
from time import sleep

channels = 1
sample_width = 2
sample_rate = 44100

audio_sink = AlsaSink()
audio_sink.change_state(channels, sample_width, sample_rate)
playback = AudioServer(audio_sink, channels * sample_width)

def force(f, *args):
    f(*args)

try:
    port = int(os.environ['PORT'])
except:
    port = 47231

server_socket = socket(AF_INET, SOCK_STREAM)
try:
    server_socket.bind(('', port))
finally:
    force(playback.stop)
server_socket.listen(1)
class AudioServer:
    def __init__(self, sink, frame_size, source=None):
        self.__sink = sink
        self.__frame_size = frame_size
        self.__audio_stream = source
        self.__buffer = b''
        self.__done = Event()
    def set_source(self, source):
        self.__audio_stream = source
    def get_source(self):
        return self.__audio_stream
    def start(self):
        self.__done.clear()
        while not self.__done.is_set():
            bts = self.__audio_stream.read()
            self.__buffer += bts
            if len(self.__buffer) >= self.__frame_size:
                lo = len(self.__buffer) % self.__frame_size
                self.__sink.write_frames(self.__buffer[:len(self.__buffer)-lo])
                self.__buffer = self.__buffer[:-lo]
    def stop(self):
        self.__done.set()

if __name__=='__main__':
    from audio.sink.alsasink import AlsaSink
    asnk = AlsaSink()
    asnk.change_state(2, 2, 44100)
    asrv = AudioServer(open('./audio/output', 'rb'), asnk, 2)
    asrv.start()

from audio.sink.alsasink import AlsaSink
from audio.source.wavesource import WaveSource

from sys import argv

wsrc = WaveSource(argv[1])

asnk = AlsaSink()
asnk.change_state(wsrc.get_num_channels(), wsrc.get_sample_width(), wsrc.get_sample_rate())

while True:
    bts = wsrc.read_frames(256)
    if not len(bts):
        break
    asnk.write_frames(bts)