Microphone interface for Unity when using WebGL build target. Matches standard Unity builtin Microphone class in interface so you can it for multiplatform projects without preprocessor defines. Pulls data from Web Audio into Unity AudioClips so it behaves roughly the same as the Microphone on other platforms.
Add a git package in the Unity package manager (UPM).
https://github.com/bnco-dev/unity-webgl-microphone.git
See UPM instructions here.
This is intended to be a drop-in replacement for Unity's Microphone class. Microphone code you have working on other platforms should work on WebGL too with minimal changes.
Here's a (hopefully) exhaustive list of the differences:
-
If
Start()
is called before the user has interacted with the web page, it can fail and return null. This is a limitation of the web. Specifically, AudioContexts cannot be started until the first user interaction. One solution is to only callStart()
after a user must have interacted with the page (i.e., after something has been clicked). You can also safely just keep calling it every few seconds until it returns a clip. -
Calling
Start()
,GetPosition()
,IsRecording()
orGetDeviceCaps()
will kick off the permissions procedure in the user's browser. During this timeStart()
will provide clips, but they will not be filled with data. You can useIsRecording()
to check whether data is currently coming in. This is similar to other platforms as there is usually a delay between Audio Clip creation and microphone input. Here though the delay time may take longer, and data may never come in if the user does not give microphone permission. There is currently no way to test if the user has declined permission. -
This package can only access the default recording device. It's probably possible to target a specific device, but it's not implemented here. Best practice for the web seems to be to use the default device anyway.
-
The recording is always looped and frequency is left to the browser to decide. Though it's possible in theory to specify your desired frequency in the browser, this only led to audio issues when I tested it.
-
Start()
will set the generated audio clips to the specified length, but they may be up to 512 samples shorter or longer than expected to simplify ring buffer behaviour in the plugin. -
Unity's audio API has limitations on WebGL.
Unity | Browser | Read-In | Loopback |
---|---|---|---|
Firefox 107 | ✅ | ❌ | |
2021.3.29f1 | Edge 108 | ✅ | ✅ |
Chromium 108 | ✅ | ✅ | |
Firefox 107 | ✅ | ❌ | |
2022.3.28f1 | Edge 108 | ✅ | ✅ |
Chromium 108 | ✅ | ✅ | |
Firefox 107 | ✅ | ❌ | |
6000.0.2f1 | Edge 108 | ✅ | ✅ |
Chromium 108 | ✅ | ✅ |
Pull requests welcome. Enjoy :)