Webview Support (React Native)
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;
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?
Unfortunately with limited development time, not all feature requests can be tackled. If you are interested in contributing this feature, please open a PR.