Reputation: 101
I found a code snippet in the form of a function to change the pitch of the audio being played. I want to change it to a function to change pitch when live input using microphone web-audio.
I have tried but it still doesn't work. I need help.
This is code:
function playSoundpitch(file, speed = 2, pitchShift = 1, loop = false, autoplay = true) {
if (pitchShift) {
audioCtx = new(window.AudioContext || window.webkitAudioContext)();
source = audioCtx.createBufferSource();
var gainNodex = audioCtx.createGain();
gainNodex.gain.value = 2; // double the volume
request = new XMLHttpRequest();
request.open('GET', file, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var audioData = request.response;
audioCtx.decodeAudioData(audioData, function(buffer) {
myBuffer = buffer;
songLength = buffer.duration;
source.buffer = myBuffer;
source.playbackRate.value = speed;
source.loop = loop;
//source.connect(audioCtx.destination);
source.connect(gainNodex);
gainNodex.connect(audioCtx.destination);
source.onended = function() {};
},
function(e) {
"Error with decoding audio data" + e.error
});
}
request.send();
source.play = source.start
} else {
source = new Audio(file)
source.playbackRate = speed
source.loop = loop
}
if (autoplay) {
source.play()
}
return source
}
var source;
source = playSoundpitch('https://sampleswap.org/samples-ghost/VOCALS%20and%20SPOKEN%20WORD/Native%20American/1392[kb]sheshone-native-vox2.wav.mp3', pitch = 0.8);
Upvotes: 2
Views: 539
Reputation: 1628
Take a look at this page : https://alligator.io/js/first-steps-web-audio-api/
The portion that is pertinent to your question is found towards the bottom :
/* The frequency (in Hz) of Bb4 is 466.16 */ oscillator .frequency .setValueAtTime(466.16, audioContext.currentTime);
Of note is that the "oscillator" object is first built, and later in the code, the pitch of node can be adjusted in-stream with the above code. You already have your node created (what you are calling your audioCtx
object). That object has a frequency value that must be changed on the fly. The case above is for a static pitch change. You will have to both acquire the frequency and then alter it by the differential of the pitch you desire, and use setValueAtTime
to update that value.
Alternatively, you can install this package and use it to make the pitch shift work easier:
https://github.com/mmckegg/soundbank-pitch-shift
Finally, there is a another solution using AudioContext object found here (using detune
method): https://codepen.io/qur2/pen/emVQwW
Upvotes: 1