Skip to content

Commit

Permalink
Fix old 16-bit normalized buffer bug.
Browse files Browse the repository at this point in the history
  • Loading branch information
chr15m committed Jun 5, 2022
1 parent 7b39c47 commit 39a6cc2
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions sfxr.js
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ sfxr.toBuffer = function(synthdef) {

sfxr.toWebAudio = function(synthdef, audiocontext) {
var sfx = new SoundEffect(synthdef);
var buffer = _sfxr_getNormalized(sfx.getRawBuffer()["buffer"], sfx.bitsPerChannel);
var buffer = sfx.getRawBuffer()["normalized"];
if (audiocontext) {
var buff = audiocontext.createBuffer(1, buffer.length, sfx.sampleRate);
var nowBuffering = buff.getChannelData(0);
Expand Down Expand Up @@ -634,6 +634,7 @@ SoundEffect.prototype.getRawBuffer = function () {
var num_clipped = 0;

var buffer = [];
var normalized = [];

var sample_sum = 0;
var num_summed = 0;
Expand Down Expand Up @@ -776,6 +777,9 @@ SoundEffect.prototype.getRawBuffer = function () {
sample = sample / OVERSAMPLING * masterVolume;
sample *= this.gain;

// store the original normalized floating point sample
normalized.push(sample);

if (this.bitsPerChannel === 8) {
// Rescale [-1, 1) to [0, 256)
sample = Math.floor((sample + 1) * 128);
Expand Down Expand Up @@ -804,32 +808,23 @@ SoundEffect.prototype.getRawBuffer = function () {

return {
"buffer": buffer,
"normalized": normalized,
"clipped": num_clipped,
}
}

SoundEffect.prototype.generate = function() {
var rendered = this.getRawBuffer();
var wave = new RIFFWAVE();
var normalized = _sfxr_getNormalized(rendered.buffer, this.bitsPerChannel);
wave.header.sampleRate = this.sampleRate;
wave.header.bitsPerSample = this.bitsPerChannel;
wave.Make(rendered.buffer);
wave.clipping = rendered.clipped;
wave.buffer = normalized;
wave.buffer = rendered.normalized;
wave.getAudio = _sfxr_getAudioFn(wave);
return wave;
}

var _sfxr_getNormalized = function(buffer, bitsPerChannel) {
// normalize buffer
var normalized = new Float32Array(buffer.length);
for (var b=0; b<buffer.length; b++) {
normalized[b] = 2.0 * buffer[b] / pow(2, bitsPerChannel) - 1.0;
}
return normalized;
}

var _actx = null;
var _sfxr_getAudioFn = function(wave) {
return function() {
Expand Down

0 comments on commit 39a6cc2

Please sign in to comment.