[docs]classAudioStream:""" Funksjonalitet: - Leser inn en lydfil i opus-format. - Sender en lydfil i rå-data over socket til WebServer. :param str file_path: Stien til filen som skal spilles av. :ivar str filepath: Stien til lydfilen. """def__init__(self,file_path,chunklength=0.05):self.filepath=file_pathself.chunklength=chunklength#self.samplerate = Noneself.chunksize=Noneself.samples=Noneself.position=0definit_stream(self):""" Oppretter en forbindelse med stream. Foreløpig ikke implementert. """logger.info("AudioStream: Started init_stream")try:withopen(self.filepath,"rb")asf:opusfiledata=f.read()logger.info(f"AudioStream: Read {len(opusfiledata)} bytes from {self.filepath}")opus_data=BytesIO(opusfiledata)logger.info("AudioStream: Created BytesIO object")self.samples=AudioSegment.from_file(opus_data,codec="opus")logger.info("AudioStream: Successfully loaded AudioSegment")self.chunksize=int(self.chunklength*1000)self.position=0logger.info(f"AudioStream: Initialized with chunksize={self.chunksize}")exceptExceptionase:logger.error(f"AudioStream: Failed to initialize stream. Error: {e}")raisedefget_next_chunk(self):""" Henter nye lydbiter Foreløpig ikke implementert. """logger.info("AudioStream: Getting next chunk")# chunk = self.samples.readframes(self.chunksize)begin=self.positionend=begin+self.chunksizechunk=self.samples[begin:end]iflen(chunk)==0:returnNoneself.position=endreturnchunk.raw_datadefstream_chunks(self):""" Sender en lydstrøm Ikke implementert enda. """logger.info("AudioStream: stream_chunks called")self.init_stream()whileTrue:chunk=self.get_next_chunk()ifchunkisNone:logger.info("AudioStream: get_next_chunk returned None, ending stream")breaklogger.info(f"AudioStream: yielding chunk of size {len(chunk)} bytes")yieldchunk
[docs]defsimple_send(self):""" Åpner en lydfil of returnerer den som rådata. Returns: bytes: Rådata opus-lydfil Raises: Exception: Hvis filen ikke kan leses eller en annen feil oppstår. """logger.info("AudioStream: sending simple file")try:withopen(self.filepath,"rb")asf:opusfiledata=f.read()logger.info(f"AudioStream: Read {len(opusfiledata)} bytes from {self.filepath}")returnopusfiledataexceptExceptionase:logger.error(f"AudioStream: failed to send simple file: {e}")raise