Hörtest-Anwendung in Javascript - Tonerzeugung
(EN google-translate)
(PL google-translate)
Schließlich wird ein Audio-Stream-Element erzeugt, das stetig einen zu füllenden Buffer bereitstellt, in den der Sampleverlauf geschrieben wird.
<!DOCTYPE html>
<html>
<head lang="de">
<meta charset="iso-8859-1">
<script language:javascript>
var frequenz = 440;
var amplitude = 100;
var zustand = -1; //-1: vor erstem Start, 1: nach erstem Start, 0: nach erstem Stop.
var context;
var node;
var x;
var data;
var wert;
function prozess(e)
{
var data = e.outputBuffer.getChannelData(0);
//2*PI*f*t == 2*PI*f*(1/Samplefrequenz)*x_test_sample
for (var i = 0; i < data.length; ++i)
{
if(zustand==1)
{
wert = (amplitude/1000.0)*Math.sin(2*Math.PI*frequenz*x/context.sampleRate);
}
else
{
wert = 0.0;
}
data[i] = wert;
x++;
}
}
function setzeFrequenz()
{
frequenz = document.getElementById("input_frequenz").value;
document.getElementById("wert_frequenz").innerHTML = frequenz;
}
function setzeAmplitude()
{
amplitude = document.getElementById("input_amplitude").value;
document.getElementById("wert_amplitude").innerHTML = amplitude;
}
function startstop()
{
if(zustand==-1)
{
x=0;
context = new (window.AudioContext || window.webkitAudioContext)();
//1. Param.: Erlaubte Puffergroessen: 256, 512, 1024, 2048, 4096, 8192, 16384
//2. Param.: Anzahl der Input-Kanaele
//3. Param.: Anzahl der Output-Kanaele
node = context.createScriptProcessor(1024, 0, 1);
node.onaudioprocess = function(e) { prozess(e) };
node.connect(context.destination); //"play"
document.getElementById("startstop").value = "AN";
document.getElementById("startstop").style.backgroundColor = "#00FF00";
zustand = 1;
}
else if(zustand==1)
{
document.getElementById("startstop").value = "AUS";
document.getElementById("startstop").style.backgroundColor = "#FF0000";
zustand = 0;
}
else //if(zustand==0)
{
document.getElementById("startstop").value = "AN";
document.getElementById("startstop").style.backgroundColor = "#00FF00";
zustand = 1;
}
}
</script>
</head>
<body>
<fieldset>
<p>
<label>Frequenz:
<input style="width:400px;" id="input_frequenz" type="range" min="1" max="20000" value="440" onmousemove="javascript:setzeFrequenz()" />
<span id="wert_frequenz">440</span>Hz</label>
</p>
<br/>
<p>
<label>Amplitude:
<input style="width:400px;" id="input_amplitude" type="range" min="0" max="700" value="100" onmousemove="javascript:setzeAmplitude()" />
<span id="wert_amplitude">100</span></label>
</p>
<p>
<input id="startstop" type="button" value="AUS" style="background-color: #FF0000" onclick="javascript:startstop()"/>
</p>
</fieldset>
</body>
</html>
Code 0-1: Quelltext.