Last active
November 3, 2024 23:31
-
-
Save chukonu/241bc6793d34cbf05de56bcae8bc012d to your computer and use it in GitHub Desktop.
a web component for playing audio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PlayUtterance extends HTMLElement { | |
constructor() { | |
super(); | |
} | |
connectedCallback() { | |
const shadow = this.attachShadow({ mode: "open" }); | |
const flx = document.createElement("div"); | |
const src = this.getAttribute("src"); | |
const lab = this.getAttribute("label"); | |
const aud = document.createElement("audio"); | |
aud.src = src; | |
aud.controls = false; | |
const labEl = document.createElement("span"); | |
labEl.style.fontWeight = "500"; | |
labEl.textContent = lab; | |
const button = document.createElement("button"); | |
button.textContent = "Play"; | |
button.style.margin = "0 0.5em"; | |
button.style.width = "6em"; | |
button.style.fontSize = "1rem"; | |
button.style.lineHeight = "1.5em"; | |
button.addEventListener("click", () => { | |
aud.play(); | |
}); | |
aud.addEventListener("play", () => { | |
button.disabled = true; | |
button.textContent = "Playing..."; | |
}); | |
aud.addEventListener("ended", () => { | |
button.disabled = false; | |
button.textContent = "Play"; | |
}); | |
flx.style.display = "flex"; | |
flx.style.alignItems = "stretch"; | |
flx.appendChild(labEl); | |
flx.appendChild(button); | |
flx.appendChild(aud); | |
shadow.appendChild(button); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment