1
- use crossbeam_channel:: { self , Receiver , Sender } ;
2
1
use rand:: Rng ;
2
+
3
+ use std:: any:: Any ;
3
4
use std:: collections:: HashMap ;
4
5
5
6
use web_audio_api:: context:: {
@@ -30,48 +31,42 @@ enum NoiseColor {
30
31
/// Audio source node emitting white noise (random samples)
31
32
struct WhiteNoiseNode {
32
33
node : AudioWorkletNode ,
33
- sender : Sender < NoiseColor > ,
34
34
}
35
35
36
36
impl WhiteNoiseNode {
37
37
fn new ( context : & AudioContext ) -> Self {
38
- // use a bounded channel for real-time safety
39
- let ( sender, receiver) = crossbeam_channel:: bounded ( 16 ) ;
40
-
41
38
let options = AudioWorkletNodeOptions {
42
39
number_of_inputs : 0 ,
43
40
number_of_outputs : 1 ,
44
41
output_channel_count : vec ! [ 1 ] ,
45
42
parameter_data : HashMap :: new ( ) ,
46
- processor_options : receiver ,
43
+ processor_options : ( ) ,
47
44
channel_config : ChannelConfigOptions :: default ( ) ,
48
45
} ;
49
46
50
47
let node = AudioWorkletNode :: new :: < WhiteNoiseProcessor > ( context. base ( ) , options) ;
51
- Self { node, sender }
48
+ Self { node }
52
49
}
53
50
54
51
fn node ( & self ) -> & AudioWorkletNode {
55
52
& self . node
56
53
}
57
54
58
55
fn set_noise_color ( & self , color : NoiseColor ) {
59
- self . sender . send ( color ) . unwrap ( ) ;
56
+ self . node . port ( ) . post_message ( color ) ;
60
57
}
61
58
}
62
59
63
60
struct WhiteNoiseProcessor {
64
61
color : NoiseColor ,
65
- receiver : Receiver < NoiseColor > ,
66
62
}
67
63
68
64
impl AudioWorkletProcessor for WhiteNoiseProcessor {
69
- type ProcessorOptions = Receiver < NoiseColor > ;
65
+ type ProcessorOptions = ( ) ;
70
66
71
- fn constructor ( opts : Self :: ProcessorOptions ) -> Self {
67
+ fn constructor ( _opts : Self :: ProcessorOptions ) -> Self {
72
68
Self {
73
69
color : NoiseColor :: White ,
74
- receiver : opts,
75
70
}
76
71
}
77
72
@@ -82,11 +77,6 @@ impl AudioWorkletProcessor for WhiteNoiseProcessor {
82
77
_params : AudioParamValues < ' _ > ,
83
78
_scope : & RenderScope ,
84
79
) -> bool {
85
- // handle incoming messages
86
- if let Ok ( color) = self . receiver . try_recv ( ) {
87
- self . color = color;
88
- }
89
-
90
80
// edit the output buffer in place
91
81
outputs[ 0 ] . iter_mut ( ) . for_each ( |buf| {
92
82
let mut rng = rand:: thread_rng ( ) ;
@@ -105,6 +95,15 @@ impl AudioWorkletProcessor for WhiteNoiseProcessor {
105
95
106
96
true // tail time, source node will always be active
107
97
}
98
+
99
+ fn onmessage ( & mut self , msg : & mut dyn Any ) {
100
+ if let Some ( & color) = msg. downcast_ref :: < NoiseColor > ( ) {
101
+ self . color = color;
102
+ return ;
103
+ }
104
+
105
+ log:: warn!( "WhiteNoiseProcessor: Ignoring incoming message" ) ;
106
+ }
108
107
}
109
108
110
109
fn main ( ) {
0 commit comments