diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0af27ad --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "deno-audio" +version = "0.1.0" +authors = ["divy-work "] +edition = "2018" +publish = false + +[lib] +path = "lib.rs" +crate-type = ["cdylib"] + +[dependencies] +rodio = "0.12.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +futures = "0.3.4" +deno_core = "0.66.0" diff --git a/README.md b/README.md new file mode 100644 index 0000000..d60f89b --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +sudo apt-get install libasound2-dev \ No newline at end of file diff --git a/lib.rs b/lib.rs new file mode 100644 index 0000000..cd20d70 --- /dev/null +++ b/lib.rs @@ -0,0 +1,47 @@ +//! Deno Audio playback library with rodio. +//! +//! The main concept of this library is to play audio from Deno. +//! +//! For example, here is how you would play an audio file: +//! +//! ```typescript +//! // example.ts +//! await play("examples/music.mp3"); +//! ``` + +use std::io::BufReader; + +use deno_core::plugin_api::Interface; +use deno_core::plugin_api::Op; +use deno_core::plugin_api::ZeroCopyBuf; +use futures::future::FutureExt; + +#[no_mangle] +pub fn deno_plugin_init(interface: &mut dyn Interface) { + interface.register_op("play", op_play); +} + +fn op_play(_interface: &mut dyn Interface, zero_copy: &mut [ZeroCopyBuf]) -> Op { + let data = &zero_copy[0][..]; + let data_str = std::str::from_utf8(&data[..]).unwrap().to_string(); + let fut = async move { + let (tx, rx) = futures::channel::oneshot::channel::>(); + std::thread::spawn(move || { + // call type_string + let (_stream, handle) = rodio::OutputStream::try_default().unwrap(); + let sink = rodio::Sink::try_new(&handle).unwrap(); + + let file = std::fs::File::open(&data_str).unwrap(); + sink.append(rodio::Decoder::new(BufReader::new(file)).unwrap()); + + sink.sleep_until_end(); + tx.send(Ok(())); + }); + let result_box = serde_json::to_vec(&rx.await.unwrap()) + .unwrap() + .into_boxed_slice(); + result_box + }; + + Op::Async(fut.boxed()) +}