Web Audio API is new for me, after researching it for a few days, but still haven’t solved the problem.
Web Audio API mentioned that audio can be obtained from HTML tags, but WebGL does not have such tags. How can I obtain the playing audio and set pitch?
Like the document states changing the pitch is unfortunately not supported on the Web Platform.
If you want to use the WebAudio API directly you could do it if you write a JavaScript plugin. But that means you can’t use any of the Unity audio features and would need to build your own Audio System and handle sound files manually(e.g. store them in StreamingAssets).
Since we have hundreds of audio clips, I wonder if there is an approach by which, I can handle a general sound output once and for all,
Like:
audioContext = new AudioContext();
audioSource= getPlayingAudioFromMemory();//pseudo code //this line is my question
gainNode= audioContext.createGain();
audioSource.connect(gainNode).connect(audioContext.destination);
I just don’t know how to get audio from Unity WebGL instance.
There is no easy way to access the sound clips from the JavaScript side. You could use Unity - Scripting API: AudioClip.GetData to read the data from C# and pass it to your JS plugin. This might be slightly inefficient but you can use the existing handling of audio assets.
The alternative would be to move all your sound files into a StreamingAssets folder in your project and use them like this:
function createAudioNodeForStreamingAsset(fileName, pitch) {
let mediaElement = new Audio();
mediaElement.preload = "metadata";
mediaElement.src = "/StreamingAssets/" + fileName;
let source = audioContext.createMediaElementSource(mediaElement);
// Change pitch
mediaElement.playbackRate = pitch;
return source;
}
let audioContext = new AudioContext();
let audioSource = createAudioNodeForStreamingAsset(fileName, pitch);
let gainNode= audioContext.createGain();
audioSource.connect(gainNode).connect(audioContext.destination);
// This will return a promise and might fail if there was no user interaction with the website
// You might want to retry on the next "click" event
audioSource.mediaElement.play()
Switch to streaming assets, automatically solved the problem.
In webGL build timeline, when timescale = 2, streaming wav files won’t be affected, simply set playback rate = 2, get a natural result (no tone change)