7

[Golang] GopherJS DOM Example - Play Sound on Click Event

 2 years ago
source link: http://siongui.github.io/2016/01/15/gopherjs-dom-example-play-sound-onclick-event/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw

<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Play Sound on Click Event</title>
</head>
<body>

<button id="foo" type="button">Click Me to Play Sound</button>
<audio id="audio">
  <source src="Wat_Metta_Buddha_Qualities.mp3" type="audio/mpeg">
Your browser does not support this audio format.
</audio>

<script src="demo.js"></script>
</body>
</html>

We will bind a onclick event handler to the button element whose id is foo. When users click the button, the play() method of HTML audio element will be called to play the sound of the mp3 file, which is Wat_Metta_Buddha_Qualities.mp3 in this example.

play.go | repository | view raw

package main

import "honnef.co/go/js/dom"

func main() {
	d := dom.GetWindow().Document()

	foo := d.GetElementByID("foo").(*dom.HTMLButtonElement)
	foo.AddEventListener("click", false, func(event dom.Event) {
		a := d.GetElementByID("audio").(*dom.HTMLAudioElement)
		// already specify source in audio tag, no need to set src
		//a.SetAttribute("src", "Wat_Metta_Buddha_Qualities.mp3")
		a.Play()
	})
}

Compile the Go code to JavaScript by:

$ gopherjs build play.go -o demo.js

Put demo.js together with the index.html and the mp3 file in the same directory. Open the index.html with your browser. Click the button and you will hear the sound!


Tested on: Ubuntu Linux 15.10, Go 1.5.3.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK