Render multi-channel audio

This commit is contained in:
Rob Watson 2020-09-09 11:52:18 +02:00
parent 4a951c6035
commit b6ca40e184
1 changed files with 27 additions and 26 deletions

View File

@ -69,8 +69,8 @@ impl Canvas {
fn redraw_canvas(&mut self) {
let canvas_element = self.canvas_node.cast::<HtmlCanvasElement>().unwrap();
let width = canvas_element.width();
let height = canvas_element.height();
let width = canvas_element.width() as f64;
let height = canvas_element.height() as f64;
let context = canvas_element
.get_context("2d")
@ -79,38 +79,39 @@ impl Canvas {
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
context.set_fill_style(&"black".into());
context.set_stroke_style(&"green".into());
context.fill_rect(0.0, 0.0, canvas_element.width() as f64, height as f64);
context.set_fill_style(&"#000000".into());
context.set_stroke_style(&"#00ff00".into());
context.fill_rect(0.0, 0.0, width, height);
if self.audio_data.is_some() {
let audio_data = self.audio_data.as_ref().unwrap();
let num_channels = audio_data.number_of_channels();
// TODO: multi-channel
let _num_channels = audio_data.number_of_channels(); // 1
for chan in 0..num_channels {
let channel_data = audio_data.get_channel_data(chan).unwrap();
let chunks = utils::chunks_fixed(&channel_data, canvas_element.width() as usize);
let channel_data = audio_data.get_channel_data(0).unwrap();
let chunks = utils::chunks_fixed(&channel_data, canvas_element.width() as usize);
chunks.enumerate().for_each(|(i, chunk)| {
let max = chunk
.iter()
.map(|v| (v * 32767.0) as i32)
.map(|v| v.abs())
.max()
.unwrap();
chunks.enumerate().for_each(|(i, chunk)| {
let max = chunk
.iter()
.map(|v| (v * 32767.0) as i32)
.map(|v| v.abs())
.max()
.unwrap();
let pc = (max as f64 / 32767.0) * 100.0;
let max_height = (height / num_channels as f64).floor();
let len = (max_height / 100.0 * pc).floor();
let mid = max_height * (chan + 1) as f64 - (max_height / 2.0);
let pc = (max as f64 / 32767.0) * 100.0;
let len = (height as f64 / 100.0 * pc).floor();
let mid = height as f64 / 2f64;
context.begin_path();
context.move_to(i as f64, mid - (len / 2.0));
context.line_to(i as f64, mid + (len / 2.0));
context.stroke();
context.begin_path();
context.move_to(i as f64, mid - (len / 2f64));
context.line_to(i as f64, mid + (len / 2f64));
context.stroke();
// ConsoleService::log(&format!("index {}: max {}, pc {}, len {}", i, max, pc, len));
});
// ConsoleService::log(&format!("index {}: max {}, pc {}, len {}", i, max, pc, len));
});
}
}
}
}