Tone.js icon indicating copy to clipboard operation
Tone.js copied to clipboard

Webview Support (React Native)

Open ttm opened this issue 10 months ago • 2 comments

We are trying to make Tone.js work in React Native using a webview: https://github.com/react-native-webview/react-native-webview

Currently, it makes no sound in iOS, but it makes some distorted sound in the Android emulator, and it doesn't crash the system in either iOS and Android.

We are considering using Kotlin and Swift to make audio work in React Native for us, if we can't make Tone.js work in the webview. Has anyone successfully used Tone.js in RN/Webview? Does anyone have advices or want to guide us in making Tone.js work in the React Native's webview?

We are using this component for testing:

const WebviewTest = () => {
  const triggerSound = () => {
    webviewRef.current.injectJavaScript(`playTone();`);
  };

  const webviewRef = useRef(null);

  return (
    <View style={styles.container}>
      <Button title="Play Sound" onPress={triggerSound} />
      <WebView
        ref={webviewRef}
        source={{
          html: `
          <html>
          <head>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/15.0.4/Tone.js"></script>
          </head>
          <body style="display:flex; justify-content:center; align-items:center; height:100vh; background:#f5f5f5;">
            <button onclick="playSound()">Play Sound</button>
            <script>
              function playSound() {
                console.log("🎵 Button pressed - Initializing Tone.js...");
                const synth = new Tone.Synth().toDestination();
                Tone.start().then(() => {
                  console.log("🔊 Tone.js Audio Context Started");
                  synth.triggerAttackRelease("C4", "2");
                }).catch(error => {
                  console.error("⚠️ Tone.js failed to start:", error);
                });
              }
            </script>
          </body>
          </html>
          `,
        }}
        style={styles.webview}
      />
    </View>
  );
};

export default WebviewTest;

ttm avatar Feb 19 '25 17:02 ttm

I haven't done it in React Native, but I have an Ionic app that uses Tone.js without any issues (which is in effect a webview). Are you not getting any errors at all? Have u tried starting the Transport with start() rather than Tone.start?

cordial avatar Mar 10 '25 17:03 cordial

Unfortunately with limited development time, not all feature requests can be tackled. If you are interested in contributing this feature, please open a PR.

github-actions[bot] avatar Jun 09 '25 02:06 github-actions[bot]