Форум программистов, компьютерный форум, киберфорум
JavaScript
Войти
Регистрация
Восстановить пароль
Другие темы раздела
JavaScript Dropdown (множественный выбор) https://www.cyberforum.ru/ javascript/ thread2750769.html
Помогите пожалуйста, имею кусок скрипта "множественнный выбор" нужно его отредактировать так что бы этот список разворачивался и сворачивался (dropdown - multi select). Пример на фото из этого отредактировать в такой вид Вот код обычного списка которого нужно отредактировать
Нейронная сеть обратного распространения JavaScript
Здравствуйте. Сейчас углубляюсь в нейросети и не могу точно понять как реализовать гибкую основу для обратного распространения. Задача будет что-то вроде распознавания используя mnist (много входных нейронов, 1-2 скрытых слоя с relu и возможно softmax активацией во втором слое, на выходе 10 нейронов). Я вроде начал разбираться по чуть-чуть с теорией и мог бы реализовать функции активации и тд.,...
JavaScript Скрипт который будет обходить блокировку рекламы https://www.cyberforum.ru/ javascript/ thread2749973.html
Нужен скрипт, который будет обходить блокировку рекламы на сайте. Например, будет переадресация на другую страницу где будет просьба отключить блокировщик или что-то другое.
JavaScript Отослать фотки с googledrive telegram, google drive share public trouble, new interface 2020 https://www.cyberforum.ru/ javascript/ thread2749687.html
Возникла проблема с публичным доступом к изображениям на гугл-диске. При попытке отослать изображения по ссылкам появляются ошибки, погуглив нахожу что нужно сделать файлы публичными, так как по умолчанию они "приватные", и тут началась возня: все ответы в гугле дают инструкцию на старый интерфейс (до весны 2020) , там присутсвует кнопка "Advanced" и 3 опции "Private," "Anyone with the link" or...
Обмен данными по UART на основе html , js JavaScript
Какие простые способы организации обмена данными по UART существуют ( прием, передача данных , управление RTS,DTR, чтение CTS,DCD,DSR, RI , изменение бодрейта , например, на 38400 бод) на основе html , js, ActiveX ? Как организовать, например, аналогично программе test_multiprog, или для обмена данными с MAYAK232ATTINY2313A_v3.06_final ? Возможно ли это только на html с встроенными скриптами...
JavaScript Валидация формы смешанного типа полей https://www.cyberforum.ru/ javascript/ thread2747965.html
Добрый вечер всем. Прошу помощи в подсказке. Есть форма типа опросника по шагам, сделал простой пример без заморочек и скрытия шагов. Так вот к чему я, если радио кнопки можно провалидировать при каждом нажатии кнопки более менее простым способом, то как можно провалидировать смешанный шаг, в котором нужно выбрать или вариант из радио кнопки или вписать что то в текстовое поле? Это вызвало...
JavaScript Скрипт для звонков через браузер и node.js Всем доброго здравия. На странице инструкции twilio browser-calls, предлагается выбрать серверный ЯП и фреймворк. После выбора php & laravel идем пошагово инструкцию с кодом и комментарием https://www.twilio.com/docs/voice/tutorials/browser-calls-php-laravel И вот на этапе когда уже есть интерфейс, пора подключать скрипты котороые сделают возможными броузерные звонки, дается скрипт /** *... https://www.cyberforum.ru/ javascript/ thread2747888.html JavaScript Построить объёмный пятиугольник с текстурой
Построить геометрию, соответствующую рисунку (12 баллов): Наложить текстуру (для каждой грани – отдельная картинка) – 13 баллов. Текстура не должна быть растянутой (нужно рассчитывать соотношение ширины / высоты текстуры, затем вычислять, какого размера должен быть геометрический объект). Пример: Ширина текстуры 1073, высота – 800, размеры объекта 2 м, тогда: 800 / 1073 = 2 / x;
JavaScript Создание чата на Websocket https://www.cyberforum.ru/ javascript/ thread2746559.html
Всем привет! Возникла у меня такая задача по созданию чата для сайта бронирования турбаз. В смысл в том, чтобы была возможность посетителю связаться с администратором турбазы для решения возникающих вопросов. Весь смысл в том, что список чатов должен обновляться по мере поступления новых сообщений, также должна быть реализована возможность добавить чат с турбазой по клику на кнопку. По отправке...
JavaScript Следы от инспектора страницы Всем привет! Не обессудьте, если вопрос направил не туда или он покажется странным... Интересен такой момент: если во время работы web-страницы (даже с работающим JS-скриптом) включить инспектор кода страницы (через F12 в Chrome/FireFox) или сохранить саму веб-страницу в html-/htm-формате, это отследит сервер? А может ли вообще? https://www.cyberforum.ru/ javascript/ thread2746496.html
JavaScript Как расположить сцену по середине экрана
Здравствуйте! Никак не могу понять каким образом можно изменить расположение окна просмотра 3D модели на сайте так, чтобы он был не на весь экран и был строго по центру. Как изменить размер сцены и рендера я уже определил, нужно просто задать нужные значения по X и Y вручную. Код моего проекта <!DOCTYPE html> <html> <head>
JavaScript Как остановить запрос? Возможно ли такое? У меня такой вопрос. у меня 3 вкладки. при нажатии на 3 вкладку у меня загр
6 / 6 / 0
Регистрация: 29.06.2018
Сообщений: 1,536
31.12.2020, 13:45  [ТС] 0

Генератор звуковых частот. - JavaScript - Ответ 15147706

31.12.2020, 13:45. Показов 5844. Ответов 14
Метки (Все метки)

Ответ

Регулировка с помощью Gain node из-за парсера детектора и шумов квантования при переключении уровней генератора кажется нелинейной . Требуется оптимизация парсера.

Добавлено через 19 минут
простая программа для масштабной сетки

Javascript
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
79
80
81
82
83
84
85
86
87
var canvasContext = null;
function InitDrawing()
{
 canvasContext = document.getElementById( "meter" ).getContext("2d");
 canvasContext.clearRect(0,0,WIDTH, HEIGHT);
}
 
 
function ClearCanvas()
{
canvasContext.clearRect(0,0,WIDTH, HEIGHT);
}
var dxPos=1;
function SetPoint(numstep,  Y ,  num)
{
var xPos=numstep*dxPos;
var yPos ;
if (dBmode==0) { yPos=HEIGHT*(1-Y); }  
if (dBmode==1)  { yPos=HEIGHT*(1-0.7)-  Y *(HEIGHT/120);  }
       canvasContext.beginPath();
       canvasContext.moveTo( xPos, HEIGHT);
       canvasContext.lineTo( xPos, yPos);  //fix
        // canvasContext.moveTo( xPos, yPos);
         //canvasContext.lineTo( xPos+1, yPos);  //fix
    if (meter.checkClipping()){  canvasContext.strokeStyle ="red"; } // тёмно-синий цвет
    else  { canvasContext.strokeStyle ="green"; }
 canvasContext.lineWidth =dxPos;
  canvasContext.stroke();
}
 
 
 
function drawlevel(Y)
{
      var yPos1=HEIGHT*(1-Y);
       ClearCanvas();
       drawGrid();
       canvasContext.beginPath();
       canvasContext.moveTo( 100, HEIGHT);
       canvasContext.lineTo(100, yPos1);  //fix
       if (meter.checkClipping()){  canvasContext.strokeStyle ="red"; }   
       else  { canvasContext.strokeStyle ="green"; }
       canvasContext.lineWidth =20;
       canvasContext.stroke();
 
}
 
   
function drawGrid()
{
 
//var canvas = document.getElementById("myCanvas");
//var canvasContext = canvas.getContext("2d");
//ClearCanvas()
var istep =50;
var jstep =0.1;
var text; 
var xdata;
for (var i=0; i< WIDTH ; i+=istep)
{
       xdata=freqmin+ (i/dxPos)*fstep;  
       text=String(   xdata.toFixed(2));
       canvasContext.font = "9px Arial"
       canvasContext.fillText(text, i,HEIGHT  );
       canvasContext.beginPath();
       canvasContext.moveTo(i, HEIGHT);
       canvasContext.lineTo(i, 0);   
       canvasContext.strokeStyle ="blue";  
       canvasContext.lineWidth =1;
       canvasContext.stroke();
}
var yCoord;
for (var j=0; j<1  ; j+=jstep)
{
      yCoord=HEIGHT*(1-j);
       text=String(j.toFixed(2));
       canvasContext.font = "9px Arial"
       canvasContext.fillText(text, 0,yCoord  );
       canvasContext.beginPath();
       canvasContext.moveTo(0, yCoord);
       canvasContext.lineTo(WIDTH,  yCoord);   
       canvasContext.strokeStyle ="blue";  
       canvasContext.lineWidth =1;
       canvasContext.stroke();
}
 
}

levelmeter.js

Javascript
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
function createAudioMeter(audioContext, clipLevel, averaging, clipLag ,   ResetVolume) 
{
 var processor = audioContext.createScriptProcessor(512); //512,fix
 processor.onaudioprocess = volumeAudioProcess;
 processor.clipping = false;
 processor.lastClip = 0;
 processor.volume = 0;
 processor.clipLevel = clipLevel || 0.98;
 processor.averaging = averaging || 0.95;
 processor.clipLag = clipLag || 750;
  processor.ResetVolume =ResetVolume;
 // this will have no effect, since we don't copy the input to the output,
 // but works around a current Chrome bug.
processor.connect(audioContext.destination);
 
processor.checkClipping =function()
{
if (!this.clipping) return false;
if ((this.lastClip + this.clipLag) < window.performance.now())  this.clipping = false;
return this.clipping;
};
 
processor.shutdown =function(){ this.disconnect(); this.onaudioprocess = null;  };
return processor;
}
 
function volumeAudioProcess( event ) {
 var buf = event.inputBuffer.getChannelData(0);
 var bufLength = buf.length;
// var sum = 0;
 var xmax= 0;
 var x;
    
 for (var i=0; i<bufLength; i++) {
 x = buf[i];
  if (Math.abs(x)>=this.clipLevel) { this.clipping = true; this.lastClip = window.performance.now();  }
  if (Math.abs(x)>=Math.abs(xmax)) { xmax=Math.abs(x); } 
 //sum += x * x;
 }
 
 // if(this.ResetVolume==1){ xmax=0;  }
 
     //var rms =  Math.sqrt(sum / bufLength);
     //  this.volume =  Math.max(rms, this.volume*this.averaging);
//   xmax*=0.707 ;  //fix for peak 
 
   this.volume = xmax; //get peak value or rms value for Um*sin(w*t)
}
перенес в отдельный модуль drawaxes.js

Линейность по переключателям (линейный вход на линейный выход ) в линейном режиме при индикации уровня при 1кГц, Input Level=16% , Output level= 10%, Aosc= 0dB(1.0), Kinp=+ 20 dB(10.0) ,

Добавлено через 58 секунд
Там еще особенность про регулировку усиления была (про не превышение 0,1...0,2 ).

Добавлено через 45 минут
Javascript
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
function CreateOsc( )
{
//audioCtxGen = new (window.AudioContext || window.webkitAudioContext)();
 oscillator = audioContext.createOscillator();
 oscillator.type = 'sine';
 gainNodeOut = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
 oscillator.connect( gainNodeOut );
//oscillator.connect(audioContext.destination);
  gainNodeOut .connect(audioContext.destination);
  gainNodeOut .gain.value =0.01*LevelOut*Kout*0.1 ;
 oscillator.frequency.setValueAtTime(currfreq, audioContext.currentTime); // value in hertz
 oscillator.start();
}
 
 
function CreateInputLevelMeter(stream)
{
//  gainNodeIn = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
//  gainNodeIn.gain.value=0;
    mediaStreamSource = audioContext.createMediaStreamSource(stream);
    meter = createAudioMeter(audioContext);
    mediaStreamSource.connect(meter); //without  Gain
//    mediaStreamSource.connect(gainNodeIn); //connect input stream to  the input node
//    gainNodeIn.connect(meter);
//    gainNodeIn.gain.value =0.01*LevelIn*Kin *10;
 
}
Свыше -40 дБ может давать шум 1,5...6 дБ , но не с материнки , а из-за способа обработки семплов и соотношения усилений , но так уровень ограничения виднее только при ограничении, еще один множитель зависит от общего регулятор а громкости .

Добавлено через 3 минуты
HTML5
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
<td>
<label for="SelKosc">Kosc</label>
<select size="1"  name="SelKosc" id="SelKosc" onchange="SelectKosc()"  >
    <option disabled>Select Kosc</option>
    <option selected value="1"> 0 dB</option>
    <option  value="0.7071">-3.0 dB </option>
    <option  value="0.50">-6.0 dB </option>
    <option  value="0.316">-10 dB </option>
    <option  value="0.1778">-15 dB </option>
    <option value="0.1">-20 dB</option>
    <option value="0.0316">-30 dB</option>
    <option value="0.010">-40 dB</option>
    <option value="0.00316">-50 dB</option>
    <option value="0.001">-60 dB</option> 
   </select>
</td>
 
...
 
<td>
<label for="SelKinp">Kinp</label>
<select size="1"  name="SelKinp" id="SelKinp" onchange="SelectKinp()"   >
    <option disabled>Select Kin </option>
       <option value="1000">  +60 dB</option>
       <option value="316">  +50 dB</option>
       <option value="100">  +40 dB</option>
       <option value="31.6">  +30 dB</option>
       <option value="10">  +20 dB</option>
    <option value="3.16">  +10 dB</option>
    <option selected value="1"> 0 dB</option>
    <option  value="0.7071">-3.0 dB </option>
    <option  value="0.50">-6.0 dB </option>
    <option  value="0.316">-10 dB </option>
    <option  value="0.1778">-15 dB </option>
    <option value="0.1">-20 dB</option>
    <option value="0.0316">-30 dB</option>
    <option value="0.010">-40 dB</option>
    <option value="0.00316">-50 dB</option>
      <option value="0.001">-60 dB</option>
   </select>
</td>
Временные контролы для дебага.

Добавлено через 4 часа 30 минут
Встроил масштабирование, приделал переключатели, изменил цвет. Можно ввести автовыбор количества меток частоты.
drawaxes.js
Javascript
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
var canvasContext = null;
function InitDrawing()
{
 canvasContext = document.getElementById( "meter" ).getContext("2d");
 canvasContext.clearRect(0,0,WIDTH, HEIGHT);
}
 
function ClearCanvas(){canvasContext.clearRect(0,0,WIDTH, HEIGHT);}
 
function ScaleY(  Ydata , pictB, pictT    )
{
 var pictH = (pictB -pictT );
 var ymin=0  ;
 var ymax=1 ;
if (dBmode==0){ ymin=0  ; ymax=1;  }
if (dBmode==1){ ymin=KminLog*1.0  ; ymax=KmaxLog*1.0  }
var  ytmp=(ymax-Ydata)/(ymax-ymin) ;  
 return ( pictB  - pictH *(1-ytmp) );      //ytmp=0...1
}
 
function ScaleX(  Xdata , pictL, pictR    )
{
 var pictW = (pictR -pictL);
 var  xmin=freqmin;
 var  xmax=freqmax;
var  xtmp=(Xdata-xmin)/(xmax-xmin) ;  
 return ( pictL+pictW*xtmp );      //xtmp=0...1
}
 
 
 
 
function SetPoint(currfreq,  ydata ,  num)
{
var pictBottom=HEIGHT*0.9 ;
var pictTop= HEIGHT*0.1;
var dxPos=1;
var xPos =ScaleX( currfreq , 20,  WIDTH );  
var yPos =ScaleY( ydata, pictBottom, pictTop);
 
 
       canvasContext.beginPath();
        //canvasContext.moveTo( xPos, pictBottom);
        //canvasContext.lineTo( xPos, yPos);  //fix
         canvasContext.moveTo( xPos, yPos);
          canvasContext.lineTo( xPos+dxPos, yPos);  //fix
    if (meter.checkClipping()){  canvasContext.strokeStyle ="red"; }  
    else  { canvasContext.strokeStyle ="green"; }
    canvasContext.lineWidth =2;
    canvasContext.stroke();
}
 
 
 
function drawlevel(xdata , ydata)
{
 
var pictBottom=HEIGHT*0.9 ;
var pictTop= HEIGHT*0.1;
      ClearCanvas();
      drawGrid();  
      var yPos1=   ScaleY(ydata , pictBottom, pictTop  ) ;  //Ydata=0...1  
      var xPos1=ScaleX( xdata  , 20,  WIDTH ); 
       canvasContext.beginPath();
       canvasContext.moveTo( xPos1, pictBottom);
       canvasContext.lineTo(xPos1, yPos1);  //fix
       if (meter.checkClipping()){  canvasContext.strokeStyle ="red"; }   
       else  { canvasContext.strokeStyle ="green"; }
       canvasContext.lineWidth =10;
       canvasContext.stroke();
}
 
 
 
   
function drawGrid ()
{
var pictBottom=HEIGHT*0.9 ;
var pictTop= HEIGHT*0.1;
 
 
//var canvas = document.getElementById("myCanvas");
//var canvasContext = canvas.getContext("2d");
//ClearCanvas()
var istep =10;
var jstep =0.1;
var text; 
var xdata;
var  xCoord,yCoord;
var y1min;
var y1max;
 
if (dBmode==0){ y1min=0  ; y1max=1 ; jstep=0.1;  }
if (dBmode==1){ y1min=KminLog*1.0  ; y1max=KmaxLog*1.0;  jstep=10; }
 
 
//draw vertical lines
for ( xdata=freqmin; xdata<=freqmax ; xdata+=fstep*20  )  //fix
{
        
        text=String(xdata.toFixed(2));
        xCoord=ScaleX( xdata , 20,  WIDTH ); 
       canvasContext.font = "9px Arial"
       canvasContext.fillText(text,  xCoord, HEIGHT  );
       canvasContext.beginPath();
       canvasContext.moveTo(xCoord, pictTop);
       canvasContext.lineTo(xCoord, pictBottom+10);   
       canvasContext.strokeStyle ="#d3d3d3";  
       canvasContext.lineWidth =1;
       canvasContext.stroke();
}
 
 
//draw horizontal lines 
for (var j=y1min;  j<=y1max ; j +=jstep)
{
       yCoord= ScaleY(  j, pictBottom, pictTop  );
       text=String(j.toFixed(1));
            
       canvasContext.font = "9px Arial"
  
       canvasContext.fillText(text, 0, yCoord  );
       canvasContext.beginPath();
       canvasContext.moveTo(0, yCoord);
       canvasContext.lineTo(WIDTH,  yCoord);   
       canvasContext.strokeStyle ="#d3d3d3";  
       canvasContext.lineWidth =1;
       canvasContext.stroke();
}
 
}
main.js

Javascript
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
 
 
var freqmin=50.0;
var freqmax=10000.0;
var currfreq= 50.0;
var fstep =50.0;
var delay=100;
var LevelIn=50;
var LevelOut=50;
 
 
var  gainNodeOut =null;
var  gainNodeIn=null;
var audioContext = null;
var meter = null;
var oscillator =null;
 
var WIDTH=1000;
var HEIGHT=300;
var timeoutID=null;
 
var stepnum=0;
var dBmode=0; 
var streammode=0;
 var Kin=1;
 var Kout=1;
 
var Kmax=1;
var Kmin=0;
 
var KmaxLog=0;
var KminLog=-120;
 
 
 
function SelectKmax()
{
Kmax=parseFloat(document.getElementById("SelKmax").options[document.getElementById("SelKmax").selectedIndex].value );
KmaxLog=20*Math.log10(Kmax);
KmaxLog=KmaxLog.toFixed(0);
 document.getElementById("LabelKmax").innerHTML = KmaxLog;
 
}
function SelectKmin()
{
Kmin=parseFloat(document.getElementById("SelKmin").options[document.getElementById("SelKmin").selectedIndex].value );
KminLog=20*Math.log10(Kmin);
KminLog=KminLog.toFixed(0);
 document.getElementById("LabelKmin").innerHTML = KminLog;
}
 
 
function SelectKosc()
{
 Kout=parseFloat(document.getElementById("SelKosc").options[document.getElementById("SelKosc").selectedIndex].value );
 document.getElementById("LabelKosc").innerHTML = Kout;
 gainNodeOut.gain.value =0.01*LevelOut *Kout*0.1 ;
}
function SelectKinp()
{
Kin=parseFloat(document.getElementById("SelKinp").options[document.getElementById("SelKinp").selectedIndex].value );
document.getElementById("LabelKinp").innerHTML = Kin;
//gainNodeIn.gain.value =0.01*LevelIn*Kin*10  ;
}
 
function  SetLevelIn()
{
LevelIn=document.getElementById("LevelInput").value;
document.getElementById("LevelIn1").innerHTML =LevelIn;
try {
gainNodeIn.gain.value =0.01*LevelIn*Kin *10;
} catch (e) { }
}
 
 
function  SetLevelOut()
{
LevelOut=document.getElementById("LevelOutput").value;
document.getElementById("LevelOut1").innerHTML =LevelOut;
try {
 gainNodeOut.gain.value =0.01*LevelOut *Kout*0.1;
} catch (e) { }
}
 
 function UpdateLabels()
{
 document.getElementById("minfreq").innerHTML =freqmin;
 document.getElementById("maxfreq").innerHTML =freqmax;
 document.getElementById("delay1").innerHTML =delay;
 document.getElementById("step1").innerHTML =fstep;
}
window.onload = function Init() {UpdateLabels(); }
  
function OnChangeFmin(){freqmin=parseFloat(document.getElementById("FminIn").value);UpdateLabels();}
function OnChangeFmax(){ freqmax =parseFloat(document.getElementById("FmaxIn").value); UpdateLabels(); }
function OnChangeDelay(){ delay =parseFloat(document.getElementById("DelayIn").value) ; UpdateLabels(); }
function OnChangeStep(){ fstep =parseFloat(document.getElementById("StepIn").value) ;UpdateLabels(); }
 
function CreateOsc( )
{
//audioCtxGen = new (window.AudioContext || window.webkitAudioContext)();
 oscillator = audioContext.createOscillator();
 oscillator.type = 'sine';
 gainNodeOut = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
 oscillator.connect( gainNodeOut );
//oscillator.connect(audioContext.destination);
  gainNodeOut .connect(audioContext.destination);
  gainNodeOut .gain.value =0.01*LevelOut*Kout*0.1 ;
 oscillator.frequency.setValueAtTime(currfreq, audioContext.currentTime); // value in hertz
 oscillator.start();
}
 
 
function CreateInputLevelMeter(stream)
{
//  gainNodeIn = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
//  gainNodeIn.gain.value=0;
    mediaStreamSource = audioContext.createMediaStreamSource(stream);
    meter = createAudioMeter(audioContext);
    mediaStreamSource.connect(meter); //without  Gain
//    mediaStreamSource.connect(gainNodeIn); //connect input stream to  the input node
//    gainNodeIn.connect(meter);
//    gainNodeIn.gain.value =0.01*LevelIn*Kin *10;
 
}
 
 var Coeffs= new Float64Array(2048);
 Coeffs.fill(1);
  
 
 function GetLevel(){    meter.ResetVolume=0;       guard_delay();      return (meter.volume*  0.01*LevelIn*Kin *10 ) ; }
 //function GetLevel(){ meter.ResetVolume=0;       guard_delay();      return (meter.volume  ) ;} 
 
 
function GetValue(Ldata , nstep1, modedB, mode1  )
{
     
var datadBIn=20*Math.log10(Ldata );
var dataIn=Ldata ;
if (mode1==1) {  datadBIn+= Coeffs [nstep1] ; dataIn*= Coeffs[ nstep1] ; } 
      document.getElementById("Vinp1").innerHTML =dataIn.toExponential(4); 
      document.getElementById("Vinp2").innerHTML =datadBIn.toFixed(1); 
 if (modedB==1)   { return datadBIn; } else { return dataIn ; }
    return dataIn ;  
}
 
function CreateNormCoefsArray(stepnum,  mode, indata )
{  
var coeftmp=1;
var i=stepnum;
if (mode==0){ coeftmp=1/(indata+(1e-12));   } //obtain coeff.   for     Level*Coeffs=1return; 
if (mode==1){ coeftmp=(-indata);  } //obtain coeff.   for     Level+Coeffs =return;
Coeffs[i]=coeftmp;
}
 
 function dsleep(milliseconds) 
{
 var start = new Date().getTime();
 for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds) {   break; } }
}
 
 
 
 function guard_delay(){ dsleep(delay); }
 
function UpdateFreqValue()
{    
 meter.ResetVolume=1; 
document.getElementById("curfreq1").innerHTML =currfreq.toFixed(2);  
//oscillator.frequency.value=currfreq; 
 oscillator.frequency.setValueAtTime(currfreq, audioContext.currentTime); 
// oscillator.frequency.linearRampToValueAtTime(currfreq, audioContext.currentTime);
}
 
 
 function NormLoop(  ) 
{
 var tmpdata;
 if (currfreq<=freqmax)
{
   document.getElementById("nstep").innerHTML =stepnum ;
   meter.ResetVolume=1;
   UpdateFreqValue(); 
    tmpdata=GetLevel();   
   CreateNormCoefsArray(stepnum,  dBmode  , GetValue(tmpdata,  stepnum, dBmode, 0 ) );
   if  ( document.getElementById("NormCoefs").checked )  { tmpdata =GetValue(tmpdata, stepnum , dBmode , 1 ) ; }
  else {  tmpdata =GetValue(tmpdata, stepnum , dBmode , 0 ) ; }
 
    SetPoint( currfreq,  tmpdata);
    currfreq +=fstep;   
    stepnum++;
  }
  else{ StopOnClick();  }
}
 
 
 function drawLoop(  ) 
{
 var tmpdata;
 if (currfreq<=freqmax)
{
 
    document.getElementById("nstep").innerHTML =stepnum ;
    meter.ResetVolume=1; 
    UpdateFreqValue(); 
     tmpdata=GetLevel();  
 
   if  ( document.getElementById("NormCoefs").checked )  { tmpdata =GetValue(tmpdata, stepnum , dBmode , 1 ) ;
} else  {  tmpdata =GetValue(tmpdata, stepnum , dBmode , 0 ) ; }
     SetPoint( currfreq,  tmpdata);
    currfreq  += fstep;   
    stepnum++;
}
else{  StopOnClick(); }
}
 
 
 function drawLoop1(  ) 
{
    var tmpdata;
  
      document.getElementById("nstep").innerHTML =0 ;
       meter.ResetVolume=1;  
       UpdateFreqValue();    
       tmpdata=GetLevel();
       tmpdata =GetValue(tmpdata, stepnum , dBmode , 0 ) ;
       drawlevel(currfreq, tmpdata);
}
 
 
function GetNumberofPoints(){ return 1+Math.ceil ((freqmax-freqmin)/fstep); }
function gotStream(stream) 
{
    CreateInputLevelMeter(stream); 
    CreateOsc( ); 
    Coeffs.length=GetNumberofPoints();
if (streammode==0){   timeoutID=setInterval( drawLoop , 50);   }
if (streammode==1){     if (dBmode==1) { Coeffs.fill(0) ; } else { Coeffs.fill(1) ; }    timeoutID=setInterval( NormLoop , 50 );  } 
if (streammode==2){     timeoutID=setInterval(  drawLoop1  , 50 );  } 
 
 } 
 
function StopOnClick()
{
 clearInterval( timeoutID);
 timeoutID=null  ;
 oscillator.stop();
 oscillator.disconnect();
 currfreq=freqmin;
 gainNodeOut =null;
 gainNodeIn=null;
 meter =null;
 mediaStreamSource = null;
 audioContext =null;
 
stepnum=0;
if(streammode==2) canvasContext.clearRect(0,0,WIDTH, HEIGHT);
}
 
 
function ClearOnClick(){ StopOnClick(); ClearCanvas();}
function ClearCoefsOnClick(){ Coeffs.length=GetNumberofPoints() ; if (dBmode==1) { Coeffs.fill(0) ; } else { Coeffs.fill(1) ; } }
 
 
function RunOnClick() 
{
(document.getElementById("LogMode").checked==true)  ? dBmode=1 : dBmode=0; 
if (dBmode==1)  { document.getElementById("currmode").innerHTML ="Log. Mode " ;}
if (dBmode==0)  { document.getElementById("currmode").innerHTML ="Lin.  Mode " ; }
 currfreq=freqmin;
 streammode=0;
 UpdateLabels();
  InitDrawing();
  drawGrid();
 CreateStream();
}
 
function NormOnClick() 
{
(document.getElementById("LogMode").checked==true)  ? dBmode=1 : dBmode=0; 
if (dBmode==1)  { document.getElementById("currmode").innerHTML ="Log. Mode " ;}
if (dBmode==0)  { document.getElementById("currmode").innerHTML ="Lin.  Mode " ; }
currfreq=freqmin;
streammode=1;
UpdateLabels();
 InitDrawing();
 drawGrid();
CreateStream();
}
 
function LevelOnClick(){
 
(document.getElementById("LogMode").checked==true)  ? dBmode=1 : dBmode=0; 
if (dBmode==1)  { document.getElementById("currmode").innerHTML ="Log. Mode " ;}
if (dBmode==0)  { document.getElementById("currmode").innerHTML ="Lin.  Mode " ; }
 
 currfreq=parseFloat(prompt('Input frequency, Hz ?', 1000.0) );
 streammode=2;
 UpdateLabels();
 InitDrawing();
 CreateStream();
 
 
}
levelmeter.js

Javascript
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
79
80
81
82
83
84
85
86
87
88
89
function createAudioMeter(audioContext, clipLevel, averaging, clipLag ,   ResetVolume) 
{
 var processor = audioContext.createScriptProcessor(512); //512,fix
 processor.onaudioprocess = volumeAudioProcess;
 processor.clipping = false;
 processor.lastClip = 0;
 processor.volume = 0;
 processor.clipLevel = clipLevel || 0.98;
 processor.averaging = averaging || 0.95;
 processor.clipLag = clipLag || 750;
  processor.ResetVolume =ResetVolume;
 // this will have no effect, since we don't copy the input to the output,
 // but works around a current Chrome bug.
processor.connect(audioContext.destination);
 
processor.checkClipping =function()
{
if (!this.clipping) return false;
if ((this.lastClip + this.clipLag) < window.performance.now())  this.clipping = false;
return this.clipping;
};
 
processor.shutdown =function(){ this.disconnect(); this.onaudioprocess = null;  };
return processor;
}
 
function volumeAudioProcess( event ) {
 var buf = event.inputBuffer.getChannelData(0);
 var bufLength = buf.length;
// var sum = 0;
 var xmax= 0;
 var x;
    
 for (var i=0; i<bufLength; i++) {
 x = buf[i];
  if (Math.abs(x)>=this.clipLevel) { this.clipping = true; this.lastClip = window.performance.now();  }
  if (Math.abs(x)>=Math.abs(xmax)) { xmax=Math.abs(x); } 
 //sum += x * x;
 }
 
 if(this.ResetVolume==1){ xmax=0;  }
 
     //var rms =  Math.sqrt(sum / bufLength);
     //  this.volume =  Math.max(rms, this.volume*this.averaging);
//   xmax*=0.707 ;  //fix for peak 
 
   this.volume = xmax; //get peak value or rms value for Um*sin(w*t)
}
var mediaStreamSource = null;
 
function didntGetStream() { alert('Stream generation failed.');  }
 
function CreateStream()
{
    window.AudioContext = window.AudioContext || window.webkitAudioContext; 
    audioContext = new AudioContext();
    try {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        navigator.getUserMedia(
        {
            "audio": {
                "mandatory": {
                    "googEchoCancellation": "false",
                    "googAutoGainControl": "false",
                    "googNoiseSuppression": "false",
                    "googHighpassFilter": "false"
                },
                "optional": []
            },
        }, gotStream, didntGetStream);
  } catch (e) { alert('getUserMedia threw exception :' + e);  }
}
 
 
 
 /*
function createSource(buffer) {
  var source = context.createBufferSource();
  var gainNode = context.createGainNode();
  source.buffer = buffer;
  source.connect(gainNode);
  gainNode.connect(context.destination);
  return {
    source: source,
    gainNode: gainNode
  };
}  
 
*/


Вернуться к обсуждению:
Генератор звуковых частот. JavaScript
Вложения
Тип файла: zip afr_html_scale.zip (6.0 Кб, 3 просмотров)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
31.12.2020, 13:45
Готовые ответы и решения:

3D-аудиовизуализация. (Преобразование звуковых частот в графику)
Как реализовать дискретное преобразование вейвлет для аудиофайла? Какие вейвлет функции...

Меняю значение высоких и низких звуковых частот
Здравствуйте! Работаю над одним генератором звуковых частот, вернее над генератором шума. Нашёл...

Генератор звуковых волн
Есть статья, описывающая, как сделать генератор синуса, прямоугольного импульса, пилы и шума:...

Генератор звуковых сигналов
Всем доброго времени суток. Дали мне задание: сделать на ардуино генератор звуковых сигналов. Что...

14
31.12.2020, 13:45
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
31.12.2020, 13:45
Помогаю со студенческими работами здесь

Генератор частот
Здравствуйте, уважаемые радиотехники помогите пожалуйста разобраться. Преподаватель дал задание...

Генератор частот
Здравствуйте! Подскажите пожалуйста код, позволяющий воспроизводить любую заданную частоту в Гц,...

Генератор произвольных частот на МК
какой алгоритм для генерации произвольной частоты на микроконтроллере? Подскажите, как добиться...

генератор частот с заданным шагом
всю голову издумал, как на меге сделать генератор частоты 1000Гц-2000Гц с шагом 1, 5 или 10Гц?

Хочу сделать генератор и дешифратор звуковых сигналов
Есть идея, но не знаю, реально ли это реализовать на ATMEGA8 (это почти всё, что я имею, ещё есть...

Генератор частот. Осталось немного доработать
Написал программу, которая генирирует звук заданной частоты на протяжение 8 секунд. Хочу, что бы он...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru