Skip to content

Commit

Permalink
deno_plugin: initial work
Browse files Browse the repository at this point in the history
  • Loading branch information
littledivy committed Nov 3, 2020
0 parents commit a1714ef
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
Cargo.lock
17 changes: 17 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "deno-audio"
version = "0.1.0"
authors = ["divy-work <[email protected]>"]
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"
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sudo apt-get install libasound2-dev
47 changes: 47 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
@@ -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::<Result<(), ()>>();
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())
}

0 comments on commit a1714ef

Please sign in to comment.