Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for accelerated audio in stereo WAV #391

Merged
merged 2 commits into from
Sep 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions chipper/webroot/js/play_audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,40 @@ document.getElementById('fileInput').addEventListener('change', async () => {

try {
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

let newBuffer;

//Verify is audio is stereio or mono and convert to mono if necessary
if(audioBuffer.numberOfChannels >1){
const monoLength = audioBuffer.length;
newBuffer = audioContext.createBuffer(1, monoLength, audioBuffer.sampleRate);

const channelData = newBuffer.getChannelData(0);
for (let i = 0; i < monoLength; i++){

channelData[i] = 0.5 * (audioBuffer.getChannelData(0)[i] + audioBuffer.getChannelData(1)[i]);


}

}else{
// if already mono, just copy
newBuffer = audioBuffer;
}



// adjust frame rate to 8000 Hz
const newSampleRate = 8000;
const newLength = Math.round(audioBuffer.length * newSampleRate / audioBuffer.sampleRate);
const newBuffer = audioContext.createBuffer(audioBuffer.numberOfChannels, newLength, newSampleRate);
const newLength = Math.round(newBuffer.length * newSampleRate / newBuffer.sampleRate);
const resampledBuffer = audioContext.createBuffer(newBuffer.numberOfChannels, newLength, newSampleRate);

for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
const oldData = audioBuffer.getChannelData(channel);
const newData = newBuffer.getChannelData(channel);
for (let channel = 0; channel < newBuffer.numberOfChannels; channel++) {
const oldData = newBuffer.getChannelData(channel);
const newData = resampledBuffer .getChannelData(channel);

for (let i = 0; i < newLength; i++) {
const oldIndex = i * audioBuffer.sampleRate / newSampleRate;
const oldIndex = i * newBuffer.sampleRate / newSampleRate;
const index0 = Math.floor(oldIndex);
const index1 = Math.min(index0 + 1, oldData.length - 1);
const fraction = oldIndex - index0;
Expand All @@ -37,7 +59,7 @@ document.getElementById('fileInput').addEventListener('change', async () => {
}

// Create a new WAV file
processedAudioBlob = await bufferToWave(newBuffer);
processedAudioBlob = await bufferToWave(resampledBuffer );
const url = URL.createObjectURL(processedAudioBlob);

// play processed audio
Expand Down
Loading