如何有条件地在 R Shiny 中播放音频剪辑?

How to conditionally play an audio clip in R Shiny?

目标

只要 position 的 reactive 值在一定范围内就播放导航音频剪辑

我试过的

根据其他问题,我发现一个按钮可以用来播放音频片段。例如:

带有操作按钮的示例

library(shiny)

addResourcePath("Music", "Music")
audio_file1 <- "Music/in 200 m turn left.mp3"



ui <- fluidPage(
  
  basicPage(
    actionButton("play", "Play the Audio")
  )
  
)



server <- function(input, output, session) {
  
  observeEvent(input$play, {
    insertUI(selector = "#play",
             where = "afterEnd",
             ui = tags$audio(src = audio_file1, type = "audio/mp3", autoplay = NA, controls = NA, style="display:none;")  
    )
  })
}


shinyApp(ui, server)

我的修改没有操作按钮

我想在位置 x 为特定值时自动播放音频剪辑。为了使问题简短,在此示例中,我在 server 内提供了 x

server <- function(input, output, session) {
  
  x <- 1
  
  observeEvent(if (x==1){return(x)}, {
    insertUI(selector = "#play",
             where = "afterEnd",
             ui = tags$audio(src = audio_file1, type = "audio/mp3", autoplay = TRUE, controls = NA, style="display:none;")  
    )
  })
}

但是,这引发了一个错误:

Warning: Error in eval_tidy: no function to return from, jumping to top level
  [No stack trace available]  

我也分别尝试使用 uiOutputrenderUI 如下(服务器部分):

  output$audioo <- renderUI({
    
    if (x > 0.5 & x < 1.5) {
    
    tags$audio(src = audio_file_200_TL, type = "audio/mp3", autoplay = TRUE, controls = NA)  
      
    } else {
      
      tags$h1("My header")
    }
  
    
    })

但是当应用程序刚刚启动时播放音频并且当x在提供的范围内时音频不播放。如何在不使用操作按钮的情况下有条件地播放音频剪辑?

所以 x 既不是 input 也不是 reactive。我们需要这个,因为 R 进程必须知道重新运行循环的时间。还有其他我不推荐的硬核解决方案,例如 shiny::invalidateLater().

试一试:

x_r <- reactive(x)

observeEvent(x_r(), {
 if (x_r() == 1) {
    insertUI(selector = "#play",
             where = "afterEnd",
             ui = tags$audio(src = audio_file1, type = "audio/mp3", autoplay = TRUE, controls = NA, style="display:none;"), immediate = TRUE 
    )
 }
})

顺便说一下,使用 insertUI 时要非常小心,我不喜欢使用它,因为我们可能会多次添加相同的元素。对我来说更优雅的策略是默认添加元素,以后只在 DOM、hide/show/edit 中编辑。我们可以使用 shinyjs 包来进行此类操作。 insertUI 经常需要 immediate = TRUE 参数。

编辑:

这个应用程序非常适合我。问题是您应用中的 x 是什么。 mp3 取自 https://samplelib.com/sample-mp3.html.

library(shiny)

addResourcePath("Music", "Music")
audio_file1 <- "Music/sample-3s.mp3"

ui <- fluidPage(

  basicPage(
    tags$div(id = "AUDIO_MY"),
    selectInput("STH", "STH", 1:10, 1)
  )

)



server <- function(input, output, session) {
  observeEvent(req(input$STH == "1"), {
    insertUI(selector = "#AUDIO_MY",
             where = "afterEnd",
             ui = tags$audio(src = audio_file1, type = "audio/mp3", autoplay = NA, controls = NA, style="display:none;")
    , immediate = TRUE)
  })
}