Chaos Project

Game Development => General Discussion => Topic started by: Heretic86 on April 15, 2021, 11:07:05 am

Title: Web Audio API - Changing Pitch and Firefox
Post by: Heretic86 on April 15, 2021, 11:07:05 am
I put together a simple page that can play back an audio file, and changes pitch by adjusting playbackRate.  Then just to get into the deeper parts of Web Audio API, I saw there was a way to create a visual output of tones in a canvas element.

After I put in the graph canvas tho, I am no longer able to adjust the pitch of an audio file by changing the playback rate, and just in Firefox, but oddly it still works in Chrome.

...
        audio.preservesPitch = false;
        audio.mozPreservesPitch = false;
        audio.webkitPreservesPitch = false;
...

    function graphAnimator(){
      requestAnimationFrame(graphAnimator);
      let fbc_array = new Uint8Array(analyzer.frequencyBinCount);
      analyzer.getByteFrequencyData(fbc_array);
      ctx.clearRect(0, 0, graph.width, graph.height);
      ctx.fillStyle = "#00FFAA";
      for (let i = 0; i < 100; i++){
        let x = i * 3;
        let h = -(fbc_array[i * 8] / 12);
        ctx.fillRect(x, 20, 2, h);
      }
    }
   
    function setupGraph(){
      graph.width = 222;
      graph.height = 20;
      ctx = graph.getContext('2d');
      aCtx = new window.AudioContext();
      analyzer = aCtx.createAnalyser();
      audio_source = aCtx.createMediaElementSource(audio);
      audio_source.connect(analyzer);
      analyzer.connect(aCtx.destination);
      graphAnimator();
    }

Is there a better way to change the pitch of audio?  Honestly, one of the things I did like a bit better about old ass RMXP was its use of MIDI files did not change the playback rate and only changed the tones, but so far, I cant find any reliable ways to play MIDI files, which might be a better solution?  Not sure, and only recently noticed too (or maybe forgotten) that changing Pitch on MP3 / Ogg files does adjust playback rate , lol!

What am I doing wrong that the pitch no longer changes in Firefox but does in Chrome?
Title: Re: Web Audio API - Changing Pitch and Firefox
Post by: Blizzard on April 21, 2021, 06:28:06 am
The thing with playback rate is that physically it always changes the pitch (that's just how sound waves work). If you want to change the playback rate without changing the pitch, what internally happens is that the sound wave is actually resampled to maintain the same pitch while speeding up or slowing down the playback rate. It probably depends on the browser whether it supports this or not. Unless you resample the waves yourself, you really won't be able to use that feature if the browser doesn't support it.