add test-clean code merge
This commit is contained in:
33
talkingq-url/utils/ audio_format.py
Normal file
33
talkingq-url/utils/ audio_format.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import io
|
||||
import wave
|
||||
|
||||
|
||||
DEFAULT_SAMPLE_RATE = 16000
|
||||
DEFAULT_CHANNELS = 1
|
||||
DEFAULT_SAMPLE_WIDTH = 2
|
||||
|
||||
|
||||
def detect_audio_format(audio_data: bytes) -> str:
|
||||
if len(audio_data) >= 12 and audio_data[:4] == b"RIFF" and audio_data[8:12] == b"WAVE":
|
||||
return "wav"
|
||||
if audio_data.startswith(b"ID3"):
|
||||
return "mp3"
|
||||
if len(audio_data) >= 2 and audio_data[0] == 0xFF and (audio_data[1] & 0xE0) == 0xE0:
|
||||
return "mp3"
|
||||
return "pcm_s16le_16k_mono"
|
||||
|
||||
|
||||
def wrap_pcm_as_wav(
|
||||
audio_data: bytes,
|
||||
*,
|
||||
sample_rate: int = DEFAULT_SAMPLE_RATE,
|
||||
channels: int = DEFAULT_CHANNELS,
|
||||
sample_width: int = DEFAULT_SAMPLE_WIDTH,
|
||||
) -> bytes:
|
||||
wav_buffer = io.BytesIO()
|
||||
with wave.open(wav_buffer, "wb") as wav_file:
|
||||
wav_file.setnchannels(channels)
|
||||
wav_file.setsampwidth(sample_width)
|
||||
wav_file.setframerate(sample_rate)
|
||||
wav_file.writeframes(audio_data)
|
||||
return wav_buffer.getvalue()
|
||||
Reference in New Issue
Block a user