Compose Multi-Platform Sounds

Sound

Sound files can be played when required. For cross-platform compatibility, sound files in WAV format are best (MP3s will play on some systems, but not all).

Sound files should be placed into an 'sounds' folder within the resources folder inside your project (see here).

Sound files need to be configured as AudioStreams and as audio Clips, then loaded when the window first renders via the LaunchedEffect window component. The clips can then be played as needed. In the example code, a play() function is added to the Clip class to make this easier.

(Note that you will need to click somewhere in this page for the audio to play correctly)


                val squeakFile = object {}.javaClass.getResource("/sounds/squeak.wav")
                val dingFile   = object {}.javaClass.getResource("/sounds/ding.wav")

                val squeakStream = AudioSystem.getAudioInputStream(squeakFile)
                val dingStream   = AudioSystem.getAudioInputStream(dingFile)
                val squeakClip = AudioSystem.getClip()
                val dingClip   = AudioSystem.getClip()

                fun main() = singleWindowApplication(
                    title = "Timer"
                ) {
                    App()
                }

                @Composable
                fun App() {
                    // Load clips into memory on first render
                    LaunchedEffect(Unit) {
                        squeakClip.open(squeakStream)
                        dingClip.open(dingStream)
                    }

                    Row() {
                        Button(
                            onClick = { squeakClip.play() }
                        ) {
                            Text(text = "Squeak!")
                        }

                        Button(
                            onClick = { dingClip.play() }
                        ) {
                            Text(text = "Ding!")
                        }
                    }
                }

                // Add a play function to the Clip class
                fun Clip.play() {
                    this.stop()             // Stop if already playing
                    this.framePosition = 0  // Rewind to start
                    this.start()            // And start playing
                }