TheSharperDev

Educating about C# and F#

Play Audio - Fable/F#

Fable brings F# to the browser. Here’s how to play an audio clip in in Fable/F#.

Play Audio

Leveraging audio is a pretty simple, though took me awhile to figure out how to target JS types.

open Fable.Core.JsInterop
open Fable.Core

//This will compile down to the JS Audio type
//I received exceptions with the attribute when this 
//was in a method, not sure what the limitation is there
let [<Global("Audio")>] audioType : Browser.Types.HTMLAudioElementType = jsNative

//any old trigger
myButton.onclick <- fun _ ->
    let audio = audioType.Create()
    audio.src <- "./pathtoaudio/test.mp3"
    audio.play()

Play Multiple Audio Clips

Trying to create multiple of these causes them to play at the same time. By default the browser doesn’t queue them or wait in between.

Here’s a solution to playing audio clips sequentially.

open Fable.Core.JsInterop
open Fable.Core

//This will compile down to the JS Audio type
//I received exceptions with the attribute when this 
//was in a method, not sure what the limitation is there
let [<Global("Audio")>] audioType : Browser.Types.HTMLAudioElementType = jsNative

//any old trigger
myButton.onclick <- fun _ ->
    let audio1 = audioType.Create()
    audio1.src <- "./pathtoaudio/test.mp3"
    let audio2 = audioType.Create()
    audio2.src <- "./pathtoaudio/test.mp3"

    audio1.onended <- fun _ ->
        audio2.play()

    audio1.play()

I am leveraging the onended event to start the next one when the first one finishes. You can string these together as many as you need.

Happy Coding!!!