How开发者_如何学JAVA can I play multiple notes at the same time to form a chord with the Firefox Audio Data API? I want to be able to fill a single array with 3 notes and play them all at the same time. Here is the code I have so far which works but the chord sounds terrible:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
// Create an Audio interface
var output = new Audio();
// Set up a mono channel at 44.1Khz
output.mozSetup( 1, 44100 );
// Create a sample buffer array
var samples = new Float32Array(22050); //22050 = 1 second
var g = 2* Math.PI * 391.995 / 44100;
var e = 2* Math.PI * 329.628 / 44100;
var c = 2* Math.PI * 261.626 / 44100;
// Fill the sample buffer array with values
for(var i=0; i<samples.length; i++){
samples[i] = Math.sin(g * i) + Math.sin(e * i) + Math.sin(c * i);
//samples[i] = Math.sin(c * i);
//samples[i] = Math.sin(g * i);
}
</script>
<!-- Play the audio out -->
<button onclick="output.mozWriteAudio( samples );">Play</button>
</body>
</html>
If you fill the samples[]
array with one note it sounds just fine. But it you fill it with multiple notes it doesn't sound anything like a chord. What do I have to change in my code to play a chord?
If you just add your samples together you are going to get strong clipping. You need to scale down the output to the max value. Try this:
samples[i] = (Math.sin(g*i) + Math.sin(e*i) + Math.sin(c*i)) / 4;
精彩评论