Generating a tone using TeaVM, Webassembly in Java

51 views Asked by At

I've adapted this Java class and it's compiling with TeaVM, the text output is good so the thing is running, but I can't get it to generate a sound.

package com.xyz;

import org.teavm.jso.dom.html.HTMLDocument;
import org.teavm.jso.webaudio.AudioContext;
import org.teavm.jso.webaudio.OscillatorNode;

public class Client {
    public static void main(String[] args) throws InterruptedException {
        var document = HTMLDocument.current();
        var div = document.createElement("div");
        div.appendChild(document.createTextNode("TeaVM generated element 3"));
        document.getBody().appendChild(div);
        
        var audioContext = AudioContext.create();
        OscillatorNode oscillator = audioContext.createOscillator();
        var g = audioContext.createGain();
        oscillator.setType(OscillatorNode.TYPE_SINE);
        oscillator.connect(g);
        g.connect(audioContext.getDestination());
        oscillator.start(0);
        Thread.sleep(10000);
        oscillator.stop(20000);
        Thread.sleep(10000);
    }
}
1

There are 1 answers

0
spl On BEST ANSWER

Okay, in this case it was the media autoplay policy in chrome:

https://developer.chrome.com/blog/autoplay/#webaudio

Workaround by starting with parameters:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --autoplay-policy=no-user-gesture-required

Hopefully in my finished app the user will have interacted with the page before the sounds are played and Chrome won't see it as a problem. I should have checked the warnings in the developer tools to find this one.