Skip to content

Commit

Permalink
Read opus bytes.
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentMazare committed Aug 20, 2024
1 parent 10743bd commit 5f31b37
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,21 @@ fn write_wav(
#[pyfunction]
#[pyo3(signature = (filename))]
fn read_opus(filename: std::path::PathBuf, py: Python) -> PyResult<(PyObject, u32)> {
let (data, sample_rate) = opus::read_ogg(&filename).w_f(filename.as_path())?;
let file = std::fs::File::open(&filename)?;
let file = std::io::BufReader::new(file);
let (data, sample_rate) = opus::read_ogg(file).w_f(filename.as_path())?;
let data = numpy::PyArray2::from_vec2_bound(py, &data)?.into_py(py);
Ok((data, sample_rate))
}

/// Reads bytes corresponding to an ogg/opus encoded file.
///
/// This returns a two dimensional array as well as the sample rate.
#[pyfunction]
#[pyo3(signature = (bytes))]
fn read_opus_bytes(bytes: Vec<u8>, py: Python) -> PyResult<(PyObject, u32)> {
let bytes = std::io::Cursor::new(bytes);
let (data, sample_rate) = opus::read_ogg(bytes).w()?;
let data = numpy::PyArray2::from_vec2_bound(py, &data)?.into_py(py);
Ok((data, sample_rate))
}
Expand All @@ -204,5 +218,6 @@ fn sphn(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(read, m)?)?;
m.add_function(wrap_pyfunction!(write_wav, m)?)?;
m.add_function(wrap_pyfunction!(read_opus, m)?)?;
m.add_function(wrap_pyfunction!(read_opus_bytes, m)?)?;
Ok(())
}
7 changes: 3 additions & 4 deletions src/opus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,9 @@ fn parse_opus_header(packet: &[u8]) -> Result<OpusHeader> {
Ok(header)
}

pub fn read_ogg<P: AsRef<std::path::Path>>(p: P) -> Result<(Vec<Vec<f32>>, u32)> {
let file = std::fs::File::open(p.as_ref())?;
let file = std::io::BufReader::new(file);
let mut packet_reader = ogg::PacketReader::new(file);
/// Read an ogg stream using the opus codec.
pub fn read_ogg<R: std::io::Read + std::io::Seek>(reader: R) -> Result<(Vec<Vec<f32>>, u32)> {
let mut packet_reader = ogg::PacketReader::new(reader);
let mut opus_decoder = None;
let mut channels = 1;
let mut all_data = vec![];
Expand Down

0 comments on commit 5f31b37

Please sign in to comment.