Example #1
0
 def test_adpcm2lin(self):
     # Very cursory test
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 1, None),
                      (b'\0' * 4, (0, 0)))
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 2, None),
                      (b'\0' * 8, (0, 0)))
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 4, None),
                      (b'\0' * 16, (0, 0)))
Example #2
0
    def test_adpcm2lin(self):
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None),
                         (b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 2, None),
                         (packs[2](0, 0xb, 0x29, -0x16, 0x72, -0xb3), (-179, 40)))
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 4, None),
                         (packs[4](0, 0xb0000, 0x290000, -0x160000, 0x720000,
                                   -0xb30000), (-179, 40)))

        # Very cursory test
        for w in 1, 2, 4:
            self.assertEqual(audioop.adpcm2lin(b'\0' * 5, w, None),
                             (b'\0' * w * 10, (0, 0)))
Example #3
0
    def test_adpcm2lin(self):
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None),
                         (b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 2, None),
                         (packs[2](0, 0xb, 0x29, -0x16, 0x72, -0xb3), (-179, 40)))
        self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 4, None),
                         (packs[4](0, 0xb0000, 0x290000, -0x160000, 0x720000,
                                   -0xb30000), (-179, 40)))

        # Very cursory test
        for w in 1, 2, 4:
            self.assertEqual(audioop.adpcm2lin(b'\0' * 5, w, None),
                             (b'\0' * w * 10, (0, 0)))
Example #4
0
    def test_adpcm2lin(self):
        self.assertEqual(audioop.adpcm2lin(b"\x07\x7f\x7f", 1, None), (b"\x00\x00\x00\xff\x00\xff", (-179, 40)))
        self.assertEqual(
            audioop.adpcm2lin(b"\x07\x7f\x7f", 2, None), (packs[2](0, 0xB, 0x29, -0x16, 0x72, -0xB3), (-179, 40))
        )
        self.assertEqual(
            audioop.adpcm2lin(b"\x07\x7f\x7f", 4, None),
            (packs[4](0, 0xB0000, 0x290000, -0x160000, 0x720000, -0xB30000), (-179, 40)),
        )

        # Very cursory test
        for w in 1, 2, 4:
            self.assertEqual(audioop.adpcm2lin(b"\0" * 5, w, None), (b"\0" * w * 10, (0, 0)))
Example #5
0
    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')
Example #6
0
    def GetSound(
        self,
        index,
        outputpath=None
    ):  #index 0 is BGM. 1, 2 and 3 is SFX. if outputpath is None, the raw mono PCM @ 8184Hz is returned instead
        if self.Loaded[2]:
            if self.SoundData[index]:
                #reverse nibbles:
                data = []
                for i in map(ord, self.SoundData[index]):
                    data.append(chr((i & 0xF) << 4 | (i >> 4)))
                data = "".join(data)

                #4bit ADPCM decode
                decoded = audioop.adpcm2lin(data, 2, None)[0]

                #write to wav:
                if outputpath:
                    f = wave.open(outputpath, "wb")
                    f.setnchannels(1)
                    f.setsampwidth(2)
                    f.setframerate(
                        8192
                    )  #possibly 8184, but not a noticable difference anyway
                    f.writeframes(decoded)
                    #f.writeframes("".join(out))
                    f.close()

                    return True
                else:
                    return decoded
            else:
                return False
Example #7
0
 def _adpcm2lin(self, data):
     import audioop
     if not hasattr(self, '_adpcmstate'):
         # first time
         self._adpcmstate = None
     data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
     return data
Example #8
0
	def GetSound(self, index, outputpath=None):#index 0 is BGM. 1, 2 and 3 is SFX. if outputpath is None, the raw mono PCM @ 8184Hz is returned instead
		if self.Loaded[2]:
			if self.SoundData[index]:
				#reverse nibbles:
				data = []
				for i in map(ord,self.SoundData[index]):
					data.append(chr((i&0xF)<< 4 | (i>>4)))
				data = "".join(data)
				
				#4bit ADPCM decode
				decoded = audioop.adpcm2lin(data, 2, None)[0]
				
				#write to wav:
				if outputpath:
					f = wave.open(outputpath, "wb")
					f.setnchannels(1)
					f.setsampwidth(2)
					f.setframerate(8192)#possibly 8184, but not a noticable difference anyway
					f.writeframes(decoded)
					#f.writeframes("".join(out))
					f.close()
					
					return True
				else:
					return decoded
			else:
				return False
 def datagram_received(self, data, addr):
     message = audioop.adpcm2lin(zlib.decompress(data), 2, None)
     buffer.put(message[0])
     if buffer_response.empty():
         self.transport.sendto(b'', addr)
     else:
         self.transport.sendto(buffer_response.get().encode(), addr)
Example #10
0
    def handleNotification(self, cHandle, data):
        #pcm = adpcm_decode(data)
        pcm2, self.state = audioop.adpcm2lin(data, 2, self.state)

        # p1 = Struct('< 40h').unpack(pcm)
        # p2 = Struct('< 40h').unpack(pcm2)
        byteorder = '<'
        rawbytes = pcm2
        b = struct.unpack(byteorder + str(len(rawbytes) // 2) + "h", rawbytes)
        # for frame in b:
        #     # print(frame)
        #     m = Struct('< h').pack(frame)
        #     # print(m)
        #     self.frames.append(m)

        # time_old = np.linspace(0, , len(pcm2))
        # time_new = np.linspace(0, duration, len(pcm2)*4)
        x = np.arange(0, len(b))
        y = np.array(b)
        # yn = y - 180
        f = interpolate.interp1d(x, y)
        xnew = np.arange(0, len(b)-1, 0.1523)
        new_pcm = f(xnew)
        self.frames.append(new_pcm.tobytes())

        self.numframes += 1
Example #11
0
    def handleNotification(self, cHandle, data):
        #pcm = adpcm_decode(data)
        pcm2, self.state = audioop.adpcm2lin(data, 2, self.state)

        # p1 = Struct('< 40h').unpack(pcm)
        # p2 = Struct('< 40h').unpack(pcm2)
        byteorder = '<'
        rawbytes = pcm2
        b = struct.unpack(byteorder + str(len(rawbytes) // 2) + "h", rawbytes)

        self.frames.append(pcm2)

        import numpy as np
        from scipy import interpolate
        # time_old = np.linspace(0, , len(pcm2))
        # time_new = np.linspace(0, duration, len(pcm2)*4)
        x = np.arange(0, len(b))
        y = np.array(b)
        yn = y - 180
        f = interpolate.interp1d(x, yn)
        xnew = np.arange(0, len(b)-1, 0.5)
        new_pcm = f(xnew)

        # self.frames.append(new_pcm)
        self.numframes += 1
Example #12
0
File: aifc.py Project: 3lnc/cpython
 def _adpcm2lin(self, data):
     import audioop
     if not hasattr(self, '_adpcmstate'):
         # first time
         self._adpcmstate = None
     data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
     return data
Example #13
0
        def bytes_to_channels(fmtChunk: FmtChunk, raw_samples: bytes,
                              size) -> list:
            if int(fmtChunk.data.bits_per_sample / 8) > 0:
                sample_len = int(fmtChunk.data.bits_per_sample / 8)
            else:
                sample_len = 0

            samples = []

            if sample_len > 0:
                for i in range(int(size / sample_len)):
                    sample = raw_samples[i * sample_len:i * sample_len +
                                         sample_len]
                    if fmtChunk.data.audio_format == 1:
                        if sample_len == 1:
                            converted_sample = int.from_bytes(
                                sample, byteorder="little", signed=False)
                        else:
                            converted_sample = int.from_bytes(
                                sample, byteorder="little", signed=True)
                    elif fmtChunk.data.audio_format == 3:
                        if sample_len == 4:
                            converted_sample = struct.unpack("f", sample)[0]
                        else:
                            converted_sample = struct.unpack("d", sample)[0]
                    elif fmtChunk.data.audio_format == 6:
                        converted_sample = int.from_bytes(audioop.alaw2lin(
                            sample, sample_len),
                                                          byteorder="little",
                                                          signed=True)
                    elif fmtChunk.data.audio_format == 7:
                        converted_sample = int.from_bytes(audioop.ulaw2lin(
                            sample, sample_len),
                                                          byteorder="little",
                                                          signed=True)
                    else:
                        print(
                            "Format zapisu danych w pliku nie jest wspierany")
                        raise Exception
                    samples.append(converted_sample)
            else:
                if fmtChunk.data.audio_format == 2:
                    ret = audioop.adpcm2lin(raw_samples,
                                            fmtChunk.data.bits_per_sample,
                                            None)
                    samples_lin = ret[0]
                    for i in range(int(len(samples_lin) / 8)):
                        sample = samples_lin[i * 8:i * 8 + 8]
                        converted_sample = int.from_bytes(sample,
                                                          byteorder="little",
                                                          signed=True)
                        samples.append(converted_sample)
                else:
                    print("Format zapisu danych w pliku nie jest wspierany")
                    raise Exception

            channels = []
            for c in range(fmtChunk.data.num_channels):
                channels.append(samples[c::fmtChunk.data.num_channels])
            return channels
Example #14
0
 def _adpcm2lin(self, data):
     with warnings.catch_warnings():
         warnings.simplefilter('ignore', category=DeprecationWarning)
         import audioop
     if not hasattr(self, '_adpcmstate'):
         # first time
         self._adpcmstate = None
     data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
     return data
Example #15
0
 def datagram_received(self, data, addr):
     message = audioop.adpcm2lin(zlib.decompress(data), 2, None)
     pair = self.socket_pair(host=addr[0], port=addr[1])
     if addr in self.connection_dict:
         self.connection_dict[addr].put_buffer(message[0])
         resp = self.connection_dict[addr].get_buffer()
         self.transport.sendto(resp, addr)
     else:
         self.connection_dict[addr] = VoiceTranscription()
         self.connection_dict[addr].put_buffer(message[0])
Example #16
0
    def handle(self, data):
        # Strip the header at the beginning of the data
        data = data[KaicongAudio.HEADER_SIZE:]

        # Decompress from ADPCM (differential) to PCM-16L (WAV) format
        result = ""
        state = None
        for i in xrange(0, len(data) - 5, 2):  #TODO: No magic numbers
            adpcmfragment = data[i:i + 2]
            (sample, state) = audioop.adpcm2lin(adpcmfragment, 2, state)
            result += sample

        return result
Example #17
0
    def handleNotification(self, cHandle, data):
        # print(self.stream.get_write_available())

        pcm, self.state = audioop.adpcm2lin(data, 2, self.state)
        b = Struct('< 40h').unpack(pcm)
        # self.frames.append(pcm)
        self.stream.write(pcm)
        free = self.stream.get_write_available()
        # print(len(pcm)//2, free)
        m = Struct('< {}h'.format(free//2)).pack(*[b[-1]]*(free//2))
        self.stream.write(m)
        # print(self.stream.get_write_available())
        self.numframes += 1
Example #18
0
 def handle(self, data):
     # Strip the header at the beginning of the data
     data = data[KaicongAudio.HEADER_SIZE:]
     
     # Decompress from ADPCM (differential) to PCM-16L (WAV) format
     result = ""
     state = None
     for i in xrange(0, len(data)-5, 2):  #TODO: No magic numbers
         adpcmfragment = data[i:i+2]
         (sample, state) = audioop.adpcm2lin(adpcmfragment, 2, state)
         result += sample
 
     return result
Example #19
0
    def finish(self):
        self.adpcmfile.close()
        print("* done recording", self.numframes, "frames")

        with open('recording.adpcm', 'rb') as f:
            adpcm = f.read()
        print(len(adpcm))
        pcm, _ = audioop.adpcm2lin(adpcm, 2, None)
        print(len(pcm))
        # data length is 20 bytes, pcm length is 80 bytes
        self.wavfile = wave.open(self.audio_filename, 'wb')
        self.wavfile.setparams((1, 2, 8000, self.numframes*40, 'NONE', 'NONE'))
        self.wavfile.writeframes(pcm)
        self.wavfile.close()
Example #20
0
    def handle(self, data):
        # Strip the header at the beginning of the data
        data = data[KaicongAudio.HEADER_SZ:]

        # Decompress from ADPCM (differential) to PCM-16L (WAV) format
        result = ""
        state = None
        for i in range(0, len(data), KaicongAudio.SAMPLE_SZ):
            adpcmfragment = data[i:i + KaicongAudio.SAMPLE_SZ]
            (sample, state) = audioop.adpcm2lin(adpcmfragment,
                                                KaicongAudio.SAMPLE_SZ, state)
            result += sample

        print(len(result))
        return result
 def handle(self, data):
     # Strip the header at the beginning of the data
     data = data[KaicongAudio.HEADER_SZ:]
     
     # Decompress from ADPCM (differential) to PCM-16L (WAV) format
     result = ""
     state = None
     for i in xrange(0, len(data), KaicongAudio.SAMPLE_SZ):
         adpcmfragment = data[i:i+KaicongAudio.SAMPLE_SZ]
         (sample, state) = audioop.adpcm2lin(
                             adpcmfragment, 
                             KaicongAudio.SAMPLE_SZ, 
                             state)
         result += sample
 
     print len(result)
     return result
Example #22
0
	def run(self):
		while 1:
			olddata = data = self.iport.readsamps(600)
			if self.do_ulaw:
				data = audioop.lin2ulaw(data, 2)
				data = audioop.ulaw2lin(data, 2)
			if self.do_adpcm:
				data, nacstate = audioop.lin2adpcm(data, 2, \
					  self.acstate)
				data, dummy = audioop.adpcm2lin(data, 2, \
					  self.acstate)
				self.acstate = nacstate
			if self.do_diff:
				olddata = audioop.mul(olddata, 2, -1)
				data = audioop.add(olddata, data, 2)
			self.oport.writesamps(data)
			fl.check_forms()
Example #23
0
	def run(self):
		while 1:
			olddata = data = self.iport.readsamps(600)
			if self.do_ulaw:
				data = audioop.lin2ulaw(data, 2)
				data = audioop.ulaw2lin(data, 2)
			if self.do_adpcm:
				data, nacstate = audioop.lin2adpcm(data, 2, \
					  self.acstate)
				data, dummy = audioop.adpcm2lin(data, 2, \
					  self.acstate)
				self.acstate = nacstate
			if self.do_diff:
				olddata = audioop.mul(olddata, 2, -1)
				data = audioop.add(olddata, data, 2)
			self.oport.writesamps(data)
			fl.check_forms()
Example #24
0
 def test_adpcm2lin(self):
     self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None),
                      (b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
     self.assertEqual(
         audioop.adpcm2lin(bytearray(b'\x07\x7f\x7f'), 1, None),
         (b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
     self.assertEqual(
         audioop.adpcm2lin(memoryview(b'\x07\x7f\x7f'), 1, None),
         (b'\x00\x00\x00\xff\x00\xff', (-179, 40)))
     self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 2, None),
                      (packs[2](0, 11, 41, -22, 114, -179), (-179, 40)))
     self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 3, None),
                      (packs[3](0, 2816, 10496, -5632, 29184, -45824),
                       (-179, 40)))
     self.assertEqual(
         audioop.adpcm2lin(b'\x07\x7f\x7f', 4, None),
         (packs[4](0, 720896, 2686976, -1441792, 7471104, -11730944),
          (-179, 40)))
     for w in (1, 2, 3, 4):
         self.assertEqual(audioop.adpcm2lin(b'\x00' * 5, w, None),
                          (b'\x00' * w * 10, (0, 0)))
Example #25
0
def read_wav(songname, mark_1=0, mark_2=0):
    file   = wave.open(songname, 'r')
    chanl  = file.getnchannels()
    smwid  = file.getsampwidth()
    smfreq = file.getframerate()
    global tframe
    tframe = file.getnframes()
    if mark_2 == 0:
	mark_2 = tframe
    #print "Channels:      "+str(chanl)
    #print "Sample Width:  "+str(smwid)
    #print "Sample Freq:   "+str(smfreq)
    #print "Total Frames:  "+str(tframe)

    frames = []
    songdata = file.readframes(mark_2)
    mark_toread = mark_2-mark_1
    for mark in range(0, mark_toread):
	pcm = audioop.adpcm2lin(songdata[mark+mark_1],2,None)
	value = struct.unpack('l', pcm[0])
	frames.append(value[0])
	#progress(mark+1, mark_toread)
    file.close()
    return frames
Example #26
0
# Compare different audio compression schemes.
Example #27
0
 def readframes(self, nframes=-1):
     import audioop
     data, nframes = self._rdr.readframes(nframes)
     data, self.__state = audioop.adpcm2lin(data, self.__width,
                                            self.__state)
     return data, nframes
Example #28
0
 def test_adpcm2lin(self):
     # Very cursory test
     self.assertEqual(audioop.adpcm2lin('\0\0', 1, None),
                      ('\0\0\0\0', (0, 0)))
Example #29
0
 def decode(self, data):
     data, self.state = audioop.adpcm2lin(data, self.width, self.state)
     return data
Example #30
0
def testadpcm2lin(data):
	# Very cursory test
	if audioop.adpcm2lin('\0\0', 1, None) <> ('\0\0\0\0', (0,0)):
		return 0
	return 1
Example #31
0
 def test_adpcm2lin(self):
     # Very cursory test
     self.assertEqual(audioop.adpcm2lin('\0\0', 1, None), ('\0\0\0\0', (0,0)))
Example #32
0
def callback(input_data, frame_count, time_info, status):
    message = audioop.lin2adpcm(input_data, 2, None)
    message = audioop.adpcm2lin(message[0], 2, None)
    return (message[0], pyaudio.paContinue)
Example #33
0
 def test_adpcm2lin(self):
     # Very cursory test
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 1, None), (b'\0' * 4, (0,0)))
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 2, None), (b'\0' * 8, (0,0)))
     self.assertEqual(audioop.adpcm2lin(b'\0\0', 4, None), (b'\0' * 16, (0,0)))
Example #34
0
import audioop
import wave

data = []
with open('output.adpcm', 'rb') as f:
    state = (None, None)
    byte = f.read(1)
    while byte != b'':
        state = audioop.adpcm2lin(byte, 4, state[1])
        data.append(state[0])
        byte = f.read(1)
wf = wave.open('output.wav', 'wb')
wf.setnchannels(2)
wf.setsampwidth(4)
wf.setframerate(44100)
wf.writeframes(b''.join(data))
wf.close()
Example #35
0
def adpcm_compress(np_array, sample_width):
    compressed = audioop.lin2adpcm(np_array, sample_width, None)
    return np.frombuffer(audioop.adpcm2lin(compressed[0], sample_width,
                                           None)[0],
                         dtype=np.int16)
 def datagram_received(self, data, addr):
     buffer.put_nowait(audioop.adpcm2lin(zlib.decompress(data), 2, None))
     if response.empty():
         self.transport.sendto(b'', addr)
     else:
         self.transport.sendto(response.get().encode(), addr)
Example #37
0
"""Stuff to parse AIFF-C and AIFF files.
Example #38
0
# Compare different audio compression schemes.
Example #39
0
serv.bind((socket.gethostname(),777))
print '\n'*90,"*"*80,"\n",' '*30,'VoIP Rxer by Godson','\n\n','*'*80,'\n'*17
ip=raw_input("\nEnter the IP of other machine \t")
comp=raw_input("\n Select one of the compression technique from the following \n\t1.mue law\n\t2.ADPCM\n")
#constants
rate=33000 # these things mean nothing. i forgot to remove them(used for some experimentation)
bits=8
channels=1
data=[]
def recv(bytes):    
    global channels,bits,rate #I used these constants for debugging, they are not used in present code
    sou=pySonic.Source()
    print "Received amount of data",len(bytes)           
    sou.Sound=pySonic.MemorySample(bytes,channels,16,44000) #It simply forms a chunk of audio from the received samples
    sou.Play()
    print "Playing..."
    while sou.IsPlaying():
       time.sleep(0)   #Lol do we need  this line!!!!!
while True:    #A continuous loop which keeps on receving,decompressing & playing the audio data.
    sample,client=serv.recvfrom(100000) #dont be scared by that number
    data.append(sample) #All samples were joined together to make a meaningful audio. 
    bytes=''.join(data) # usually this called buffering. This one considerably slows down the program
    data=[]
    print "decoding..."
    if comp=='1':
        ulaw=audioop.ulaw2lin(bytes,4) #recovering original samples
        recv(ulaw)
    else:
        k=audioop.adpcm2lin(bytes,4,None)        
        recv(k[0])   
Example #40
0
def _decode_adpcm(sounddata, width, step=None):
    return sounddata
    return audioop.adpcm2lin(sounddata, width, step)