首页 > 解决方案 > 如果不知道路径/来源,如何在 Shiny 中播放音频文件?

问题描述

对于闪亮的应用程序,我希望能够播放会话本身生成的音频文件。如果它是我要上传的音频文件,我会使用

    tags$audio(src = "www/name.wav", type = "audio/wav")

但是,如果在会话期间生成音频文件,我找不到使用 tags$audio 的方法,因此我没有文件名或路径。关于如何播放此类音频文件的任何建议?谢谢!

编辑:我添加了一个简短的可重现示例。希望它变得更清楚我想要做什么。

    url <- "http://www.wavlist.com/humor/001/911d.wav"

    # Define the temporary directory and download the data
    dest_path <- "sound.wav"
    download.file(url,destfile = dest_path)

    # Load the audio file
    test <- audio::load.wave(dest_path)

    # Change something small to this audio file
    test <- test + 0.3

我现在的问题是如何在tags$audio(src = "", type = "audio/wav")没有路径的情况下使用 玩“测试” src = ""

标签: raudioshiny

解决方案


一种可能性是将生成的文件复制到文件www夹中,并用于renderUI创建您的音频标签。下面是一个关于如何实现这一目标的示例。希望这可以帮助!

library(shiny)
library(shinyjs)
library(audio)
library(seewave)

ui <- fluidPage(
  textInput('my_url','URL:',value="http://www.wavlist.com/humor/001/911d.wav"),
  uiOutput('my_audio')
)

server <- function(input, output, session){

  # Render the audio player
  output$my_audio <- renderUI({

    url <- input$my_url

    # Define the temporary directory and download the data
    dest_path <- "sound.wav"
    download.file(url,destfile = dest_path)
    # Load the audio file
    test <- audio::load.wave(dest_path)
    # Change something small to this audio file
    test <- test + 0.3
    savewav(test,filename = 'www/myaudio.wav')

      tags$audio(id='my_audio_player',
                 controls = "controls",
                 tags$source(
                   src = markdown:::.b64EncodeFile('www/myaudio.wav'),
                   type='audio/ogg; codecs=vorbis'))

  })
}

shinyApp(ui = ui, server = server)

推荐阅读