Skip to content

Commit

Permalink
Potentially resample when writing opus files.
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentMazare committed Aug 20, 2024
1 parent 2b41b52 commit 23b1e17
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ Cargo.lock
__pycache__

bria.mp3
bria.wav
bria.opus
10 changes: 7 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,21 +191,25 @@ fn write_wav(
}

#[pyfunction]
#[pyo3(signature = (filename, data, sample_rate))]
#[pyo3(signature = (filename, data, sample_rate, resample_to=None))]
fn write_opus(
filename: std::path::PathBuf,
data: numpy::PyReadonlyArray1<f32>,
sample_rate: u32,
resample_to: Option<u32>,
) -> PyResult<()> {
let w = std::fs::File::create(&filename).w_f(filename.as_path())?;
let mut w = std::io::BufWriter::new(w);
let data = data.as_array();
match data.as_slice() {
None => {
let data = data.to_vec();
opus::write_ogg(&mut w, data.as_ref(), sample_rate).w_f(filename.as_path())?
opus::write_ogg(&mut w, data.as_ref(), sample_rate, resample_to)
.w_f(filename.as_path())?
}
Some(data) => {
opus::write_ogg(&mut w, data, sample_rate, resample_to).w_f(filename.as_path())?
}
Some(data) => opus::write_ogg(&mut w, data, sample_rate).w_f(filename.as_path())?,
}
Ok(())
}
Expand Down
17 changes: 16 additions & 1 deletion src/opus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ fn write_opus_tags<W: std::io::Write>(w: &mut W) -> std::io::Result<()> {
Ok(())
}

pub fn write_ogg<W: std::io::Write>(w: &mut W, pcm: &[f32], sample_rate: u32) -> Result<()> {
fn write_ogg_<W: std::io::Write>(w: &mut W, pcm: &[f32], sample_rate: u32) -> Result<()> {
let mut pw = ogg::PacketWriter::new(w);

// Write the opus headers and tags
Expand Down Expand Up @@ -152,3 +152,18 @@ pub fn write_ogg<W: std::io::Write>(w: &mut W, pcm: &[f32], sample_rate: u32) ->

Ok(())
}

pub fn write_ogg<W: std::io::Write>(
w: &mut W,
pcm: &[f32],
sample_rate: u32,
resample_to: Option<u32>,
) -> Result<()> {
match resample_to {
None => write_ogg_(w, pcm, sample_rate),
Some(resample_to) => {
let pcm = crate::audio::resample(pcm, sample_rate as usize, resample_to as usize)?;
write_ogg_(w, &pcm, resample_to)
}
}
}
1 change: 1 addition & 0 deletions test/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@
print(data.shape, sr)

sphn.write_wav("bria.wav", data[0], sr)
sphn.write_opus("bria.opus", data[0], sr, resample_to=48000)

0 comments on commit 23b1e17

Please sign in to comment.