TIL 2: Set up Playwright with fake audio
Playwright is a popular test runner for frontend web applications. For web applications recording audio at some point in their lifecycle, some additional setup is required.
When a web application accesses a client’s microphone, it is most likely using the getUserMedia
browser API. Without any configuration, Playwright hangs when this method is called, and always fails the test (when it shouldn’t). I believe this API has simply not been implemented in Playwright’s browser implementations.
To make it work, we have to make some adjustments in the “projects” section of playwright.config.ts
:
projects: [
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
// added
launchOptions: {
args: [
"--use-fake-ui-for-media-stream",
"--use-fake-device-for-media-stream",
],
},
},
},
{
name: "firefox",
use: {
...devices["Desktop Firefox"],
// added
launchOptions: {
firefoxUserPrefs: {
"media.navigator.permission.disabled": true,
"media.navigator.streams.fake": true,
},
},
},
}
...
]
As you can see, we’ve added some launch options to the chromium
and firefox
projects. These options are passed to the browser when its process is started. In essence, the mediaStream
APIs are worked around by faking the streams. The solution came from this useful GitHub thread.
You might (rightfully) be wondering: “what about WebKit?”.
Even after looking very hard, I could unfortunately not find a workaround for WebKit. I also couldn’t find any documentation on its launch parameters, and I wasn’t about to spend much more time on it. If you have an idea, let me (and the world) know about it in the comments!