-
-
-
/
-
-
-
-`;
-
-customElements.define('sm-audio', class extends HTMLElement {
- constructor() {
- super();
- this.attachShadow({ mode: 'open' }).append(smAudio.content.cloneNode(true))
-
- this.playing = false;
- }
- static get observedAttributes() {
- return ['src']
- }
- play() {
- this.audio.play()
- this.playing = false;
- this.pauseBtn.classList.remove('hide')
- this.playBtn.classList.add('hide')
- }
- pause() {
- this.audio.pause()
- this.playing = true;
- this.pauseBtn.classList.add('hide')
- this.playBtn.classList.remove('hide')
- }
-
- get isPlaying() {
- return this.playing;
- }
-
- connectedCallback() {
- this.playBtn = this.shadowRoot.querySelector('.play');
- this.pauseBtn = this.shadowRoot.querySelector('.pause');
- this.audio = this.shadowRoot.querySelector('audio')
- this.playBtn.addEventListener('click', e => {
- this.play()
- })
- this.pauseBtn.addEventListener('click', e => {
- this.pause()
- })
- this.audio.addEventListener('ended', e => {
- this.pause()
- })
- let width;
- if ('ResizeObserver' in window) {
- let resizeObserver = new ResizeObserver(entries => {
- entries.forEach(entry => {
- width = entry.contentRect.width;
- })
- })
- resizeObserver.observe(this)
- }
- else {
- let observer = new IntersectionObserver((entries, observer) => {
- if (entries[0].isIntersecting)
- width = this.shadowRoot.querySelector('.audio').offsetWidth;
- }, {
- threshold: 1
- })
- observer.observe(this)
- }
- this.audio.addEventListener('timeupdate', e => {
- let time = this.audio.currentTime,
- minutes = Math.floor(time / 60),
- seconds = Math.floor(time - minutes * 60),
- y = seconds < 10 ? "0" + seconds : seconds;
- this.shadowRoot.querySelector('.current-time').textContent = `${minutes}:${y}`
- this.shadowRoot.querySelector('.track').style.width = (width / this.audio.duration) * this.audio.currentTime + 'px'
- })
- }
-
- attributeChangedCallback(name, oldValue, newValue) {
- if (oldValue !== newValue) {
- if (name === 'src') {
- if (this.hasAttribute('src') && newValue.trim() !== '') {
- this.shadowRoot.querySelector('audio').src = newValue;
- this.shadowRoot.querySelector('audio').onloadedmetadata = () => {
- let duration = this.audio.duration,
- minutes = Math.floor(duration / 60),
- seconds = Math.floor(duration - minutes * 60),
- y = seconds < 10 ? "0" + seconds : seconds;
- this.shadowRoot.querySelector('.duration').textContent = `${minutes}:${y}`;
- }
- }
- else
- this.classList.add('disabled')
- }
- }
- }
-})
-
//switch
const smSwitch = document.createElement('template')
smSwitch.innerHTML = `