def test_lin2alaw(self): self.assertEqual(audioop.lin2alaw(datas[1], 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') self.assertEqual(audioop.lin2alaw(datas[2], 2), b'\xd5\x87\xa4\x24\xaa\x2a\x55') self.assertEqual(audioop.lin2alaw(datas[4], 4), b'\xd5\x87\xa4\x24\xaa\x2a\x55')
def testlin2alaw(data): if verbose: print 'lin2alaw' if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \ audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \ audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5': return 0 return 1
def test_lin2alaw(self): self.assertEqual(audioop.lin2alaw(datas[1], 1), b'\xd5\x87\xa4$\xaa*Z') self.assertEqual(audioop.lin2alaw(bytearray(datas[1]), 1), b'\xd5\x87\xa4$\xaa*Z') self.assertEqual(audioop.lin2alaw(memoryview(datas[1]), 1), b'\xd5\x87\xa4$\xaa*Z') for w in (2, 3, 4): self.assertEqual(audioop.lin2alaw(datas[w], w), b'\xd5\x87\xa4$\xaa*U')
def test_lin2alaw(self): self.assertEqual(audioop.lin2alaw(datas[1], 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') self.assertEqual(audioop.lin2alaw(bytearray(datas[1]), 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') self.assertEqual(audioop.lin2alaw(memoryview(datas[1]), 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') for w in 2, 3, 4: self.assertEqual(audioop.lin2alaw(datas[w], w), b'\xd5\x87\xa4\x24\xaa\x2a\x55')
def compress(self): read = wave.open(self.create_wave(), 'rb') string_wav = np.fromstring(read.readframes(-1), 'Int16') if (self.compression_mod == "a-LAW"): compressed_string = audioop.lin2alaw(string_wav, read.getsampwidth()) compressed_string = audioop.alaw2lin(compressed_string, read.getsampwidth()) self.working_signal = np.frombuffer(compressed_string, dtype='Int16') if (self.compression_mod == "u-LAW"): compressed_string = audioop.lin2ulaw(string_wav, read.getsampwidth()) compressed_string = audioop.ulaw2lin(compressed_string, read.getsampwidth()) self.working_signal = np.frombuffer(compressed_string, dtype='Int16') if (self.compression_mod == "ADPCM"): compressed_string = audioop.lin2adpcm(string_wav, read.getsampwidth(), None) compressed_string = audioop.adpcm2lin(compressed_string[0], read.getsampwidth(), None) self.working_signal = np.frombuffer(compressed_string[0], dtype='Int16')
def _inout(self, linear, stream_time, userdata): # logger.debug('audio capture %d', len(linear)) self._ts += 160 if self.media and (self.media.hasYourFormat(self._pcmu) or self.media.hasYourFormat(self._pcma)): if self._outqueue: # logger.debug('sending packet from out queue, not mic') linear8 = self._outqueue.pop(0) else: linear8, self._resample1 = audiospeex.resample(linear, input_rate=self.sample_rate, output_rate=8000, state=self._resample1) if self.media.hasYourFormat(self._pcmu): fmt, payload = self._pcmu, audioop.lin2ulaw(linear8, 2) elif self.media.hasYourFormat(self._pcma): fmt, payload = self._pcma, audioop.lin2alaw(linear8, 2) self.media.send(payload=payload, ts=self._ts, marker=False, fmt=fmt) if self._queue: fmt, packet = self._queue.pop(0) linear8 = None if str(fmt.name).lower() == 'pcmu' and fmt.rate == 8000 or fmt.pt == 0: linear8 = audioop.ulaw2lin(packet.payload, 2) elif str(fmt.name).lower() == 'pcma' and fmt.rate == 8000 or fmt.pt == 8: linear8 = audioop.alaw2lin(packet.payload, 2) if linear8: self._record.write(linear8) if self._thqueue is not None: self._thqueue.put(linear8) linear, self._resample2 = audiospeex.resample(linear8, input_rate=8000, output_rate=self.sample_rate, state=self._resample2) # logger.debug('audio play %d', len(linear)) return linear return ''
def test_a_law_companding(self): quantization_channels = 256 compression_param = 83.7 waveform = self.waveform.clone() if not waveform.is_floating_point(): waveform = waveform.to(torch.get_default_dtype()) waveform /= torch.abs(waveform).max() self.assertTrue(waveform.min() >= -1. and waveform.max() <= 1.) waveform_a = transforms.ALawEncoding(quantization_channels, compression_param)(waveform) self.assertTrue(waveform_a.min() >= 0. and waveform_a.max() <= quantization_channels) waveform_exp = transforms.ALawDecoding(quantization_channels, compression_param)(waveform_a) self.assertTrue(waveform_exp.min() >= -1. and waveform_exp.max() <= 1.) segment_length = 1 small_int_waveform = waveform.to(torch.uint8) waveform_bytes = bytearray(small_int_waveform[0, :]) encoded = audioop.lin2alaw(waveform_bytes, segment_length) torch_encoded = transforms.ALawEncoding(quantization_channels, compression_param)(small_int_waveform) self.assertEqual(torch.tensor(list(encoded)), torch_encoded[0]) decoded = audioop.alaw2lin(encoded, segment_length) torch_decoded = transforms.ALawDecoding(quantization_channels, compression_param)(torch_encoded) self.assertEqual(torch.tensor(list(decoded)), torch_decoded[0])
def _inout(self, linear, stream_time, userdata): # logger.debug('audio capture %d', len(linear)) self._ts += 160 if self.media and (self.media.hasYourFormat(self._pcmu) or self.media.hasYourFormat(self._pcma)): linear8, self._resample1 = audiospeex.resample( linear, input_rate=44100, output_rate=8000, state=self._resample1 ) if self.media.hasYourFormat(self._pcmu): fmt, payload = self._pcmu, audioop.lin2ulaw(linear8, 2) elif self.media.hasYourFormat(self._pcma): fmt, payload = self._pcma, audioop.lin2alaw(linear8, 2) self.media.send(payload=payload, ts=self._ts, marker=False, fmt=fmt) if self._queue: fmt, packet = self._queue.pop(0) linear8 = None if str(fmt.name).lower() == "pcmu" and fmt.rate == 8000 or fmt.pt == 0: linear8 = audioop.ulaw2lin(packet.payload, 2) elif str(fmt.name).lower() == "pcma" and fmt.rate == 8000 or fmt.pt == 8: linear8 = audioop.alaw2lin(packet.payload, 2) if linear8: linear, self._resample2 = audiospeex.resample( linear8, input_rate=8000, output_rate=44100, state=self._resample2 ) # logger.debug('audio play %d', len(linear)) return linear return ""
def test_alaw2lin(self): encoded = b"\x00\x03\x24\x2a\x51\x54\x55\x58\x6b\x71\x7f" b"\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff" src = [ -688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106, 688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106, ] for w in 1, 2, 4: self.assertEqual(audioop.alaw2lin(encoded, w), packs[w](*(x << (w * 8) >> 13 for x in src))) encoded = bytes(range(256)) for w in 2, 4: decoded = audioop.alaw2lin(encoded, w) self.assertEqual(audioop.lin2alaw(decoded, w), encoded)
def read(self, samples, CODING_MODE = PCMUMODE): #Encode data using mu-law or a-law data, eod = ('', False) if self.isopen: if self.mode == TTSMODE: data, eod = self.ttsdevice.read(samples) elif self.mode == OSMODE: data = self.osdevice.read(samples) elif self.mode == FILEMODE: data, eod = self.filedevice.read(samples) if CODING_MODE == PCMUMODE: data = audioop.lin2ulaw(data, 2) elif CODING_MODE == PCMAMODE: data = audioop.lin2alaw(data, 2) #For future implementation of GSM EFR # elif CODING_MODE == GSMMODE: # data = self.gsm_encoder.encode(data) #Else the data is going to be sent as RAW data return data, eod else: print "Error reading data... please check if the device is opened..." return data, eod
def testalaw2lin(data): if verbose: print 'alaw2lin' # Cursory d = audioop.lin2alaw(data[0], 1) if audioop.alaw2lin(d, 1) != data[0]: return 0 return 1
def saveFile(self, fichWAV): self.save = False resp = "".join(self.liSave) tx = audioop.lin2alaw(resp, 2) frames = audioop.alaw2lin(tx, 2) wf = wave.open(fichWAV, "wb") wf.setnchannels(1) wf.setsampwidth(self.samplewith) wf.setframerate(16000) wf.writeframes(frames) wf.close()
def _convert_data(self, data: bytes, to_depth: int, to_channels: int, to_rate: int, to_unsigned: bool = False) -> bytes: """Convert audio data.""" out_width = to_depth // 8 if self._from_float: ldata = audioop.tomono(data, self._width, 1, 0) rdata = audioop.tomono(data, self._width, 0, 1) for mono_data in [ldata, rdata]: float_array = array('f', mono_data) out_array = array('i' if self._out_depth > 16 else 'h') for i in float_array: if i > 1.0: i = 1.0 elif i < -1.0: i = -1.0 out_array.append(round(i * 32767.0)) mono_data = out_array.tobytes() ldata = audioop.tostereo(ldata, self._width, 1, 0) rdata = audioop.tostereo(rdata, self._width, 0, 1) data = audioop.add(ldata, rdata, self._width) if self._to_alaw: data = audioop.lin2alaw(data, self._width) if self._depth != to_depth: data = audioop.lin2lin( data, self._width, out_width ) if self._unsigned != to_unsigned: data = audioop.bias(data, out_width, 128) # Make it stereo if self._channels < to_channels: data = audioop.tostereo(data, out_width, 1, 1) # Make it mono elif self._channels > to_channels: data = audioop.tomono(data, out_width, 1, 1) # Convert the sample rate of the data to the requested rate. if self._rate != to_rate and data: data, self._state = audioop.ratecv( data, out_width, to_channels, self._rate, to_rate, self._state, ) return data
def FuncionCall(self, in_data, frame_count, time_info, status): if (self.pttOn): audio = in_data encSoundData = audioop.lin2alaw(audio, 2) tosend = bytearray() # creo el paquete tosend.extend(bytes([0,0,0,0,0,0,0,0]))#para raspy tosend.extend(encSoundData) # le agrego el sonido self.udpCallback.sendto(tosend, (self.ipPtt, 60006)) else: if(len(self.ipHabilitadas)>0): audio = in_data encSoundData = audioop.lin2alaw(audio, 2) tosend = bytearray() # creo el paquete tosend.extend(bytes([0,0,0,0,0,0,0,0]))#para raspy tosend.extend(encSoundData) # le agrego el sonido for ip in self.ipHabilitadas: self.udpCallback.sendto(tosend, (ip,60006)) return (in_data, pyaudio.paContinue)
def test_alaw2lin(self): encoded = b'\x00\x03\x24\x2a\x51\x54\x55\x58\x6b\x71\x7f'\ b'\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff' src = [-688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106, 688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106] for w in 1, 2, 4: self.assertEqual(audioop.alaw2lin(encoded, w), packs[w](*(x << (w * 8) >> 13 for x in src))) encoded = ''.join(chr(x) for x in xrange(256)) for w in 2, 4: decoded = audioop.alaw2lin(encoded, w) self.assertEqual(audioop.lin2alaw(decoded, w), encoded)
def test_alaw2lin(self): # Cursory d = audioop.lin2alaw(data[0], 1) self.assertEqual(audioop.alaw2lin(d, 1), data[0]) if endian == 'big': self.assertEqual(audioop.alaw2lin(d, 2), b'\x00\x08\x01\x08\x02\x10') self.assertEqual(audioop.alaw2lin(d, 4), b'\x00\x08\x00\x00\x01\x08\x00\x00\x02\x10\x00\x00') else: self.assertEqual(audioop.alaw2lin(d, 2), b'\x08\x00\x08\x01\x10\x02') self.assertEqual(audioop.alaw2lin(d, 4), b'\x00\x00\x08\x00\x00\x00\x08\x01\x00\x00\x10\x02')
def channels_to_bytes(fmtChunk: FmtChunk, contents) -> bytes: combined_channels = [None] * (len(contents.samples) * len(contents.samples[0])) for c in range(0, fmtChunk.data.num_channels): combined_channels[c::fmtChunk.data. num_channels] = contents.samples[c] bytes_sample = b"" bytes_samples = [] for sample in combined_channels: if fmtChunk.data.bits_per_sample >= 8: sample_len = int(fmtChunk.data.bits_per_sample / 8) else: sample_len = int(fmtChunk.data.bits_per_sample / 4) if fmtChunk.data.audio_format == 1: if sample_len == 1: bytes_sample = int.to_bytes(sample, byteorder="little", signed=False, length=sample_len) else: bytes_sample = int.to_bytes(sample, byteorder="little", signed=True, length=sample_len) elif fmtChunk.data.audio_format == 3: if sample_len == 4: bytes_sample = bytearray(struct.pack("f", sample)) else: bytes_sample = bytearray(struct.pack("d", sample)) elif fmtChunk.data.audio_format == 6: bytes_sample = audioop.lin2alaw( int.to_bytes(sample, byteorder="little", signed=True, length=sample_len), sample_len) elif fmtChunk.data.audio_format == 7: bytes_sample = audioop.lin2ulaw( int.to_bytes(sample, byteorder="little", signed=True, length=sample_len), sample_len) else: raise Exception bytes_samples.append(bytes_sample) return b"".join(bytes_samples)
def micFinal(self): self.stream.stop_stream() self.stream.close() self.p.terminate() resp = "".join(self.datos) tx = audioop.lin2alaw(resp, 2) frames = audioop.alaw2lin(tx, 2) io = StringIO.StringIO() wf = wave.open(io, 'wb') wf.setnchannels(self.CHANNELS) wf.setsampwidth(self.p.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(frames) self.wav = io.getvalue() wf.close() self.centesimas = len(self.datos) * self.CHUNK * 100 / self.RATE
def test_alaw2lin(self): encoded = ( b'\x00\x03$*QTUXkq\x7f\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff' ) src = [ -688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106, 688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106 ] for w in (1, 2, 3, 4): decoded = packs[w](*(x << w * 8 >> 13 for x in src)) self.assertEqual(audioop.alaw2lin(encoded, w), decoded) self.assertEqual(audioop.alaw2lin(bytearray(encoded), w), decoded) self.assertEqual(audioop.alaw2lin(memoryview(encoded), w), decoded) encoded = bytes(range(256)) for w in (2, 3, 4): decoded = audioop.alaw2lin(encoded, w) self.assertEqual(audioop.lin2alaw(decoded, w), encoded)
def micFinal(self): self.stream.stop_stream() self.stream.close() self.p.terminate() resp = b"".join(self.datos) tx = audioop.lin2alaw(resp, 2) frames = audioop.alaw2lin(tx, 2) io = BytesIO() wf = wave.open(io, "wb") wf.setnchannels(self.CHANNELS) wf.setsampwidth(self.p.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(frames) self.wav = io.getvalue() wf.close() self.centesimas = len(self.datos) * self.CHUNK * 100 / self.RATE
def process(out, alawout): state = None while True: l, data = inp.read() if l: data = audioop.tomono(data, 4, 1, 1) # data = audioop.mul(data, 4, 4) # (data, state) = audioop.ratecv(data, 4, 1, 48000, 8000, state) avg = audioop.rms(data, 4) alaw = audioop.lin2alaw(data, 4) if a and i and a != i: level = float(avg - i) / float(a - i) print("." * int(level * 100)) out.write(data) alawout.write(alaw)
def _convert(data: bytes, width: int) -> bytes: return audioop.lin2alaw(data, width)
def test_alaw2lin(self): # Cursory d = audioop.lin2alaw(data[0], 1) self.assertEqual(audioop.alaw2lin(d, 1), data[0])
def test_lin2alaw(self): self.assertEqual(audioop.lin2alaw(data[0], 1), '\xd5\xc5\xf5') self.assertEqual(audioop.lin2alaw(data[1], 2), '\xd5\xd5\xd5') self.assertEqual(audioop.lin2alaw(data[2], 4), '\xd5\xd5\xd5')
def _lin2alaw(self, data): import audioop return audioop.lin2alaw(data, 2)
def _encode(self, bytes): return audioop.lin2alaw(bytes, 2)
def a_law_compress(np_array, sample_width): compressed = audioop.lin2alaw(np_array, sample_width) return np.frombuffer(audioop.alaw2lin(compressed, sample_width), dtype=np.int16)
def _startAudioMonitoring(self): try: log.debug("initializing Alsa PCM device") inp = alsaaudio.PCM( alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device="dmic_sv", # babyphone # cardindex=2, # dev pi ) inp.setchannels(2) inp.setrate(48000) inp.setformat(alsaaudio.PCM_FORMAT_S32_LE) inp.setperiodsize(320) log.debug("...initialization done") maxRms = (1 << 31) - 1 # only 15 because it's signed lastSent = time.time() start = time.time() sampleState = None samples = [] while True: if not self._running.is_set(): log.info("Stopping audio monitoring by signal") break l, data = inp.read() if not l: continue try: data = audioop.tomono(data, 4, 1, 1) (data, sampleState) = audioop.ratecv(data, 4, 1, 48000, 8000, sampleState) data = audioop.mul(data, 4, 2) rms = audioop.rms(data, 4) asyncio.run_coroutine_threadsafe( self._multicastAudio(audioop.lin2alaw(data, 4), time.time() - start), loop=self._loop, ) samples.append(float(rms) / float(maxRms)) if time.time() - lastSent >= 1.0: level = np.quantile(samples, 0.75) samples = [] lastSent = time.time() asyncio.run_coroutine_threadsafe( self.broadcast({ "action": "volume", "volume": level }), loop=self._loop, ) except audioop.error as e: log.debug("error in audioop %s. continuing..." % str(e)) continue except (asyncio.CancelledError, CancelledError) as e: log.info("Stopping audio monitoring since the task was cancelled") except Exception as e: log.error("Error monitoring audio") log.exception(e)
def _encode(self, payload): assert isinstance(payload, bytes), "payload is not an instance of bytes" return audioop.lin2alaw(payload, 2)
def encode(self, frame): return audioop.lin2alaw(mono_8khz(frame), frame.sample_width)
def encode(self, frame, force_keyframe=False): return audioop.lin2alaw(mono_8khz(frame), frame.sample_width)
s=socket(AF_INET, SOCK_DGRAM) s.bind(('',18294)) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) s.settimeout(1.0) s.sendto(b'', ('255.255.255.255', 18294)) send_t = time.time() outfile = open('data', 'w') outfile2 = open('data.bin', 'wb') sine = numpy.round(numpy.sin(numpy.arange(0, numpy.pi*2*20, numpy.pi*2*20/1000)) * 0) # 16384) sine_lin = b'' for i in range(len(sine)): sine_lin += struct.pack("<h", int(sine[i])) sine_alaw = audioop.lin2alaw(sine_lin, 2) sine_packet = '\x00' * 8 + sine_alaw stream_started = False start = time.time() while True: if time.time() - send_t > 1: s.sendto(b'', ('255.255.255.255', 18294)) send_t = time.time() try: m = s.recvfrom(1024) except timeout: m = None
def _lin2alaw(self, data): with warnings.catch_warnings(): warnings.simplefilter('ignore', category=DeprecationWarning) import audioop return audioop.lin2alaw(data, 2)