Skip to content

Instantly share code, notes, and snippets.

@3demax
Last active September 5, 2022 21:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3demax/4653037 to your computer and use it in GitHub Desktop.
Save 3demax/4653037 to your computer and use it in GitHub Desktop.
Simple sound recorder for opus codec
import ipdb
import pyaudio
from time import sleep
import opus
from opus import decoder as opus_decoder
from opus import encoder as opus_encoder
DEBUG = True
def log(string):
if DEBUG:
print(string)
class Audio(object):
audio_format = pyaudio.paInt16
rate = 8000
chunk = 50
channels = 2
frame = 160
seconds_in_frame = 0.02
class PyAudio(Audio):
def open_audio(self):
p = pyaudio.PyAudio()
self.input_stream = p.open(
format = self.audio_format,
channels = self.channels,
rate = self.rate,
input = True,
output = False,
frames_per_buffer = self.chunk
)
self.output_stream = p.open(
format = self.audio_format,
channels = self.channels,
rate = self.rate,
input = False,
output = True,
frames_per_buffer = self.chunk
)
def close_audio(self):
for stream in [self.input_stream, self.output_stream]:
stream.close()
aud = PyAudio()
aud.open_audio()
#codec = audio.OpusCodec()
encoder = opus_encoder.Encoder(
aud.rate,
aud.channels,
opus_encoder.APPLICATION_TYPES_MAP['voip']
)
decoder = opus_decoder.Decoder(
aud.rate,
aud.channels,
)
frm = aud.input_stream.read(aud.frame) # 8000Hz/(1000ms/20ms) - one frame
print("len raw %d" % len(frm))
raw = list()
recorded = list()
def save(data):
global raw
raw.append(data)
def recode(data):
snd = decoder.decode(encoder.encode(data, aud.frame), frame_size=aud.frame)
return snd
#ipdb.set_trace()
for i in range(0,50*3):
frm = aud.input_stream.read(aud.frame) # 8000Hz/(1000ms/20ms) - one frame
save(frm)
sumlen=0
for i in raw:
sumlen += len(i)
print "raw sumlen %d" % sumlen
recorded = map(recode, raw)
sumlen=0
for i in recorded:
sumlen += len(i)
print "encdec sumlen %d" % sumlen
#ipdb.set_trace()
print("real")
for i in raw:
aud.output_stream.write(i)
sleep(1)
print("recoded")
for i in recorded:
aud.output_stream.write(i[0:int(len(i)/2)])
aud.close_audio()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment