-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
18 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,26 @@ | ||
import os | ||
import numpy as np | ||
import opusenc | ||
import pytest | ||
import wave | ||
import librosa | ||
|
||
src = "test.wav" | ||
sample_rate = 48000 | ||
channels = 1 | ||
audio, sr = librosa.load("tests/test.wav", sr=sample_rate, mono=True) | ||
|
||
def encode_with_opus(input_file, output_file, sample_rate=48000, channels=1): | ||
audio, sr = librosa.load(input_file, sr=sample_rate, mono=True) | ||
# Convert to numpy array (16-bit integers, little-endian) | ||
audio_array = (audio * 32767).astype(np.int16) | ||
audio_array = audio_array.reshape(-1, channels) | ||
|
||
# Convert to numpy array (16-bit integers, little-endian) | ||
audio_array = (audio * 32767).astype(np.int16) | ||
audio_array = audio_array.reshape(-1, channels) | ||
|
||
# Create Opus encoder | ||
encoder = opusenc.OpusBufferedEncoder(sample_rate, channels, bitrate=160 * 1000) | ||
|
||
# Encode the audio | ||
# encoded_data = encoder.write(audio_array) | ||
encoded_data = b'' | ||
# Write in chunks | ||
for idx in range(0, len(audio_array), 1024): | ||
encoded_data += encoder.write(audio_array[idx:idx+1024]) | ||
encoded_data += encoder.flush() | ||
# Create Opus encoder | ||
encoder = opusenc.OpusBufferedEncoder(sample_rate, channels) | ||
|
||
# Write the encoded data to a file | ||
with open(output_file, 'wb') as f: | ||
f.write(encoded_data) | ||
# Encode the audio | ||
# encoded_data = encoder.write(audio_array) | ||
encoded_data = b"" | ||
# Write in chunks | ||
for idx in range(0, len(audio_array), 1024): | ||
encoded_data += encoder.write(audio_array[idx : idx + 1024]) | ||
encoded_data += encoder.flush() | ||
|
||
# Example usage | ||
output_file = "output.opus" | ||
encode_with_opus(src, output_file) | ||
# Write the encoded data to a file | ||
with open("output.opus", "wb") as f: | ||
f.write(encoded_data) |
Binary file not shown.