Audio files in R markdown

Reading documentation and Imitating is a great way to learn too !

What you need to keep in mind:

  • When you use html_document with Rmarkdown, you'll get html at the end
  • I you provide directly in you Rmd some html code it will be kept as is in markdown and during the conversion in html by pandoc
  • When you want to do some advanced customisation that does not seems to be an included feature of Rmarkdown or any :package:, you'll always get the possibility to use HTML and CSS directly.

About your example

I think you don't need the <html> and </html> surrouding your audio tag. This will do

<audio controls>
  <source src="reprex.wav" type="audio/wav">
</audio>

You can also now do some R function to create this. To play with HTML, in a R way, htmltoos :package: is really good. It is used behind shiny also. You can easily generates tags to include in markdown document. They will be recognized very well in notebook and Rmd.

html_tag_audio <- function(file, type = c("wav")) {
  type <- match.arg(type)
  htmltools::tags$audio(
    controls = NA,
    htmltools::tags$source(
      src = file,
      type = glue::glue("audio/{type}", type = type)
    )
  )
}

html_tag_audio("reprex.wav", type = "wav")

will generate this html code

<audio controls>
    <source src="reprex.wav" type="audio/wav"/>
</audio>

You can include directly in a Rmarkdown document

---
output:
  html_document
---

```{r setup, include = FALSE}
html_tag_audio <- function(file, type = c("wav")) {
  type <- match.arg(type)
  htmltools::tags$audio(
    controls = "",
    htmltools::tags$source(
      src = file,
      type = glue::glue("audio/{type}", type = type)
    )
  )
}
```

```{r}
html_tag_audio("reprex.wav", type = "wav")
```

Now that your issue is resolved, would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

3 Likes