Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Created August 3, 2016 13:11
Show Gist options
  • Select an option

  • Save cobalamin/e9508a36362b75d6578032bedac99e55 to your computer and use it in GitHub Desktop.

Select an option

Save cobalamin/e9508a36362b75d6578032bedac99e55 to your computer and use it in GitHub Desktop.
module AudioControl exposing (..)
import Html exposing (Attribute, Html, audio, div, text, button)
import Html.Attributes exposing (class, controls, type', src, id, property)
import Html.App as App
import Html.Events exposing (on, onClick)
import Json.Decode as Json
import Json.Encode as Enc
import Debug
main =
App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ mediaUrl : String
, mediaType : String
, currentTime : Float
}
-- MSG
type Msg
= NoOp
| TimeUpdate Float
-- INIT
init : ( Model, Cmd Msg )
init =
{ mediaUrl = "http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg"
, mediaType = "audio/ogg"
, currentTime = 0.0
}
! []
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
TimeUpdate time ->
( { model | currentTime = time }, Cmd.none )
_ ->
Debug.log "Unknown message" ( model, Cmd.none )
-- Custom event handler
onTimeUpdate : (Float -> msg) -> Attribute msg
onTimeUpdate msg =
on "timeupdate" (Json.map msg targetCurrentTime)
-- A `Json.Decoder` for grabbing `event.target.currentTime`.
targetCurrentTime : Json.Decoder Float
targetCurrentTime =
Json.at [ "target", "currentTime" ] Json.float
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
div [ class "elm-audio-player" ]
[ audio
[ src model.mediaUrl
, id "audio-player"
, type' model.mediaType
, controls True
, onTimeUpdate TimeUpdate
, property "currentTime" (Enc.float model.currentTime)
]
[]
, div [] [ text (toString model.currentTime) ]
, button [ onClick (TimeUpdate 2.0) ] [ text "Set current time to 2s" ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment