How to make Chrome and/or Firefox play <audio> elements in Karma tests?
Found it, at least for firefox. <audio>
elements apparently have stronger CORS rules than I realized! I was setting a Access-Control-Allow-Origin: *
header on my file server, because I knew it was on a different port then where Karma was running my tests, but apparently that's not enough.
I can't seem to find any documentation on this anywhere, but I happened to notice a chrome Error about CORS and did a little more digging & experimentation. It seems that scriptProcessors for cross-domain <audio>
elements need the the same crossOrigin
attribute that <img>
tags need to use their content in a <canvas>
.
So, in the end, going from
var audioElement = new Audio(); audioElement.src = "http://localhost:9877/audio.wav";
to
var audioElement = new Audio(); audioElement.crossOrigin = "anonymous"; audioElement.src = "http://localhost:9877/audio.wav";
Solved the issue for me in firefox, and chrome works sometimes but seems to have some other issues (perhaps related to load time?).
I believe the second issue in chrome is that I was calling .play()
right away and then ending my test when it emitted an ended
event.. but that event seems to also fire when the buffer runs empty, which I think is a bug. I changed it to wait on the canplaythrough
event before calling .play()
and it seems to be reliably passing the test now.
Some browser implementations will block attempts to automatically play <audio>
elements unless a user interaction has occurred (for obvious reasons).
There are several suggestions in this similar question, but they are all attempting to circumvent a designed feature and would probably not be very reliable across multiple browsers / devices.
Depending on your setup and which browsers you are targeting, you might need to factor in a 'click to start' button in your test.