How do I embed a Spotify song in Rmarkdown

How do I embed a Spotify song in Rmarkdown. For example, here is the code that Spotify provides -


<iframe src="https://open.spotify.com/embed/track/1dmES1X8l1AnFBy2gR3wYA" width="100%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>

How can I emed this in Rmarkdown so the song can be played?

You can paste the html directly into an rmarkdown document. However, to have it render correctly you need to do one of the following:

Set self_contained: false in the YAML metadata:

```
output:
  html_document:
    self_contained: false
```

or, add data-external="1" as an attribute in the html:

<iframe src="https://open.spotify.com/embed/track/1dmES1X8l1AnFBy2gR3wYA" width="100%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media" data-external="1"></iframe>

These options are described in this answer.

I confirmed that both options still work. However, note that the embedded music link will not appear in the RStudio html viewer that pops up when you knit the document. But if you click "open in browser" in the upper right corner, the music link will display properly.

With last knitr version (>= 1.34), you can safely use knitr::include_url() even in self contained document.
So this would work.

---
title: "Include spotify"
output: html_document
---
  
```{r, out.extra=c('allow="encrypted-media"', 'allowtransparency="true"', 'frameBorder="0"')}
knitr::include_url("https://open.spotify.com/embed/track/1dmES1X8l1AnFBy2gR3wYA", height = "380")
```
  • knitr::include_url() will create the iframe for you
  • out.extra allows you to add attributes
  • data-external = 1 trick for pandoc will be added for you - no need to remember.

If you use directly html code in the Rmd document like described above, I would suggest to mark the text explicitly as html (and you'll need the data-external="1" for Pandoc to keep the url decoded.

```{=html}
<iframe src="https://open.spotify.com/embed/track/1dmES1X8l1AnFBy2gR3wYA" width="100%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media" data-external="1"></iframe>
```

This is the safest way to write raw blocks

Hope it helps !

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.