Skip to content

Instantly share code, notes, and snippets.

@giavac
Created July 5, 2023 09:32
Show Gist options
  • Save giavac/4f4c83aa09a881d6434c29ba6cc5294b to your computer and use it in GitHub Desktop.
Save giavac/4f4c83aa09a881d6434c29ba6cc5294b to your computer and use it in GitHub Desktop.
Get a raw opus file in, decode it into a wav file
#!/usr/bin/python3
import binascii
import opuslib
import wave
total_len = 0
def process_audio_data(audio_data, wav_file):
# print(binascii.hexlify(audio_data))
print("data len:", len(audio_data))
global total_len
total_len += len(audio_data)
print("TOTAL LEN:", total_len)
# decoder = opuslib.Decoder(48000, 1)
decoder = opuslib.Decoder(8000, 1)
try:
decoded_data = decoder.decode(audio_data, 960)
print("Decoded data:", decoded_data)
print("Decoded data len:", len(decoded_data))
except opuslib.OpusError as e:
print("OpusError: {0}".format(e))
wav_file.writeframesraw(decoded_data)
def extract_audio_data(filename, ofilename, ptype):
with wave.open(ofilename, "wb") as wav_file:
wav_file.setsampwidth(2)
wav_file.setnchannels(1)
wav_file.setframerate(8000)
with open(filename, "rb") as binary_file:
print("in file open")
data = binary_file.read()
start = 0
ptype_hex = hex(ptype)[2:]
search_string = b"\x80" + bytes.fromhex(ptype_hex)
while True:
pos = data.find(search_string, start)
if pos == -1:
break
end = data.find(search_string, pos + 1)
if end == -1:
end = len(data)
if (len(data) < 40):
print("data[2]:", data[pos+2])
end = data.find(search_string, pos + 1)
if end == -1:
end = len(data)
# RTP header: 12 bytes
audio_data = data[pos + 12:end]
process_audio_data(audio_data, wav_file)
start = end
extract_audio_data("opus.raw", "decoded.wav", 97)
print("TOTAL LEN:", total_len)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment