summaryrefslogtreecommitdiff
path: root/server/modules/audio.py
blob: 693860607b472001176acaf678bdf125d6cbb4dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
    Handles the audio stream module connection.
    Setting up the output stream & making sure
    it's cleaned up from memory & data structures.
    Independent of failure or success.

    Verified: 2021 February 7
    * Follows PEP8
    * Tested Platforms
        * Windows 10
    * Third Party Modules
        * pyaudio
'''

from server.modules.module import Module
from shared.helper import Helper
from server.state import Dynamic
from shared.error import Error
from shared.data import Data

import pyaudio


class Audio(Module):

    def __init__(self, conn, token, connect_ip):
        super().__init__(conn, token, connect_ip)
        self.__audio = pyaudio.PyAudio()

    @Error.quiet_thread
    def __recv(self, channels, rate):
        try:
            try:
                stream = self.__audio.open(format=pyaudio.paInt16,
                                           channels=channels, rate=rate,
                                           frames_per_buffer=Data.BUFFER_SIZE,
                                           output=True)

                try:
                    with self.conn as sock:
                        while True:
                            stream.write(Data.recv(sock, True, False))
                            Data.send(sock)
                finally:
                    stream.stop_stream()
                    stream.close()
            finally:
                self.__audio.terminate()
        finally:
            del Dynamic.MODULES[self.token]

    def live(self, *args):
        Helper.thread(self.__recv, *args)