Skip to content

Instantly share code, notes, and snippets.

@kafecho
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kafecho/d1ab241e59134be0f944 to your computer and use it in GitHub Desktop.
Save kafecho/d1ab241e59134be0f944 to your computer and use it in GitHub Desktop.
1st attempt at a ScalaJS / Media Source Extensions demo
/**
* Work in progress....
* Let's try to port Eric Bidelman's demo (http://html5-demos.appspot.com/static/media-source.html) to ScalaJS.
* This is mostly a learning exercise.
* Only tested on Google Chrome (on OS X Yosemite).
*/
package tutorial.webapp
import scala.scalajs.js.JSApp
import org.scalajs.dom
import org.scalajs.dom._
import org.scalajs.dom.EventTarget
import scala.scalajs.js.annotation.JSName
@JSName("MediaSource")
/** Create a Scala class that maps to the MediaSource JavaScript class
* See http://www.scala-js.org/doc/calling-javascript.html
* The equivalent JavaScript that creates and instance is: new MediaSource();
*/
class MediaSource extends EventTarget{
def addSourceBuffer(s: String) : SourceBuffer = ???
}
/** Partial definition of the SourceBuffer JavaScript interface with a Scala trait.
* The ScalaJS technique is described at http://www.scala-js.org/doc/calling-javascript.html
* See http://w3c.github.io/media-source/#sourcebuffer for information on the SourceBuffer
*/
trait SourceBuffer extends EventTarget {
def appendBuffer(buffer: Uint8Array) = ???
}
/** Create a Scala object to get access to the top-level JavaScript URL object.
* See the Math example at http://www.scala-js.org/doc/calling-javascript.html
*/
object URL extends dom.URL
/** Main application logic */
object TutorialApp extends JSApp {
def main() : Unit = {
val video = document.querySelector("video").asInstanceOf[HTMLVideoElement]
val mediaSource = new MediaSource
video.src = URL.createObjectURL(mediaSource)
/** This callback is invoked when the media source is open.
* As soon as it is open, we load a webm fragment and add it to the underlying buffer so we can play.
* The code already looks spaghetti-ish with two levels of callback, so I will try to re-write it using futures or actors (if possible).
*/
val onSourceOpen = { (event: Event) =>
val sourceBuffer = mediaSource.addSourceBuffer("video/webm; codecs=\"vorbis,vp8\"");
val xhr = new XMLHttpRequest()
xhr.open("GET", "test.webm")
xhr.responseType = "arraybuffer"
xhr.onload = (e: Event) => {
if (xhr.status == 200){
val blob = xhr.response.asInstanceOf[Uint8Array]
sourceBuffer.appendBuffer(blob)
video.play()
}else{
alert(s"Unexpected status ${xhr.status} code.")
}
}
xhr.send()
}
mediaSource.addEventListener("sourceopen", onSourceOpen, false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment