Search code examples
raudioshiny

How to make a Shiny App beep / play a sound after a reactive event?


I would like a Shiny app to play a sound after a reactive event.

I already know a solution to this at the end of an R script.

On Shiny I tried:

library(shiny)
library(beepr)

ui <- fluidPage(
    tags$head(tags$script(src = "message-handler.js")),
    actionButton("dobeep", "Play sound")
)

server <- function(input, output, session) {
    observeEvent(input$dobeep, {
        #Beeps on local machine/server
        beepr::beep()

        #Doesn't beep on client
        insertUI(selector = "#dobeep",
                 where = "afterEnd",
                 ui = tags$audio(src = "beep.wav", type = "audio/wav", autoplay = T, controls = NA, style="display:none;")
        )
    })
}

shinyApp(ui, server)

I put beep.wavin the app.R directory.
On local machine, I hear the beepr::beep(), but I don't hear the audio tag from the client.
In client/server mode, I hear nothing.
In both cases, the audio Tag doesn't seem to work.
Thanks for your help.


Solution

  • The beep.wav file should be in the /www folder, located in the same directory as the shiny app for the audio Tag to work, see following post.

    This works :

    library(shiny)
    
    ui <- fluidPage(
        tags$head(tags$script(src = "message-handler.js")),
        actionButton("dobeep", "Play sound")
    )
    
    server <- function(input, output, session) {
        observeEvent(input$dobeep, {
            insertUI(selector = "#dobeep",
                     where = "afterEnd",
                     # beep.wav should be in /www of the shiny app
                     ui = tags$audio(src = "beep.wav", type = "audio/wav", autoplay = T, controls = NA, style="display:none;")
            )
        })
    }
    
    shinyApp(ui, server)