1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//! Basic Web Demo for Tunes
//!
//! This example demonstrates the Tunes audio engine running in WebAssembly.
//! It plays a simple piano melody using the browser's Web Audio API.
//!
//! # Building for Web
//!
//! 1. Install wasm-pack:
//! ```bash
//! cargo install wasm-pack
//! ```
//!
//! 2. Build the example:
//! ```bash
//! wasm-pack build --target web --features web
//! ```
//!
//! 3. Serve the HTML file with a local web server:
//! ```bash
//! python3 -m http.server 8000
//! ```
//! Then open http://localhost:8000/examples/web_demo.html
//!
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn run_web_demo() -> std::result::Result<(), JsValue> {
// Set panic hook for better error messages in the browser console
console_error_panic_hook::set_once();
web_sys::console::log_1(&"Initializing Tunes audio engine...".into());
// Create audio engine
let engine = AudioEngine::new()
.map_err(|e| JsValue::from_str(&format!("Failed to create audio engine: {}", e)))?;
web_sys::console::log_1(&"Audio engine created successfully!".into());
// Create a composition with a simple melody
let mut comp = Composition::new(Tempo::new(120.0));
web_sys::console::log_1(&"Creating melody...".into());
// Play a simple melody using synthesis
comp.instrument("piano", &Instrument::electric_piano())
.notes(&[C4, E4, G4, C5], 0.5)
.notes(&[C5, G4, E4, C4], 0.5);
web_sys::console::log_1(&"Created composition with piano melody".into());
// Convert to mixer and play (non-blocking in web environment)
let mixer = comp.into_mixer();
let id = engine.play_mixer_realtime(&mixer)
.map_err(|e| JsValue::from_str(&format!("Failed to play mixer: {}", e)))?;
web_sys::console::log_1(&format!("Playing mixer with ID: {}", id).into());
web_sys::console::log_1(&"Tunes web demo complete! You should hear a C major arpeggio.".into());
Ok(())
}
fn main() {
#[cfg(not(target_arch = "wasm32"))]
{
println!("This example is for WebAssembly only.");
println!("Build it with: wasm-pack build --target web --features web");
}
#[cfg(target_arch = "wasm32")]
{
// On WASM, the function is called via run_web_demo() from JavaScript
// No main function execution needed
}
}