Embedding Youtube and Soundcloud Content Nicely with jQuery09 Oct 2013
The first incarnation of my music page contained a simple list of plain <a href> links to site hosting the content, usually Youtube, Soundcloud or Grooveshark. While this did meet my most basic requirements of maintaining a list of songs I like, having to leave the page to view the content, only to hit my back button to return and select the next song was clunky to me. To solve this I wanted to embed the video content right onto the page, at the same time still leave the ‘list like’ format for conciseness.
Creating the embedable <iframe> for Youtube was fairly straight forward. Grab the url, parse out the ‘v’ parameter, then copy paste Google’s iframe syntax populated with the parameter. Boom, embedable glorious Youtube content.
Soundcloud’s embedable content was a bit more difficult because the URL they use in the <iframe> is not a straight derivative of the URL a person would use to view content on their website. Thankfully Soundcloud has a great API and with a little python magic I could fetch the whole <iframe> source straight from web service call.
Now in possession of embedable content from my favorite providers I needed a way to display this content neatly. I decided to search for a way to create a collapsible <div>. Something that would allow me to still see the artist and song in list form, but additionally allow me to view the content without leaving the page. John Snyder created an awesome jQuery plugin that does exactly that.
This is a rough example of how I retrieve the Soundcloud <iframe> HTML. You can see how the URL used to view content on the Soundcloud webpage is ‘url’ parameter in the API call. They offer several output formats, I choose JSON since I was already using it to parse the Reddit data coming back from their API
import urllib.request, urllib.error, urllib.parse import json def fetch_soundcloud_embed_html(): url = 'http://soundcloud.com/oembed?format=json&url=https://soundcloud.com/mat_zo/the-mat-zo-mix-004-21-09-13&iframe=true' opener = urllib.request.build_opener() try: url = urllib.request.Request(url) r = opener.open(url).read() output = r.decode('utf-8') html = json.loads(output)["html"] return html except Exception as e: logging.error(e)