The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Start, Stop, And Replay With The Web Audio API

TODO: Pull subtitle into page object

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Start, Stop, And Replay With The Web Audio API


NOTE: There's a little silence at the start of 
the track so you won't hear anything for a second
or so after hitting the button. 

-- html

<button id="startStopButton">Start At Beginning</button>

-- script
-- show
-- title: JavaScript

class Player {

  constructor() {
    this.audioContext = null
    this.isPlaying = false
    this.tracks = [
  { id: "gracie", url: "/assets/audio/gracie.mp3" },
  { id: "paino", url: "/assets/audio/plucks.mp3" }
    ]
  }

  togglePlay() {
    if (this.isPlaying === false) {
      this.startAtBeginning()
    } else {
      this.stop()
    }
  }

  startAtBeginning() {
    console.log("Starting At Beginning")
    this.isPlaying = true
    startStopButton.innerText = "Stop"
    let offset = 0
    this.audioContext = new AudioContext()
    this.tracks.forEach(async (track) => {
      const response = await fetch(track.url);
      const arrayBuffer = await response.arrayBuffer();
      track.track = await this.audioContext.decodeAudioData(arrayBuffer);
      track.source = new AudioBufferSourceNode(this.audioContext, {
        buffer: track.track,
      });
      track.source.connect(this.audioContext.destination);
      if (offset == 0) {
        track.source.start();
        offset = this.audioContext.currentTime;
      } else {
        track.source.start(0, this.audioContext.currentTime - offset);
      }
    })
  }

  stop() {
    console.log("Stopping")
    this.isPlaying = false 
    this.tracks.forEach(async (track) => {
      track.source.stop();
    })
    startStopButton.innerText = "Start At Beginning"
  }

}

document.addEventListener("DOMContentLoaded", () => {
  const p = new Player()
  startStopButton.addEventListener("click", () => { p.togglePlay() })
});


-- categories
-- JavaScript 
-- Web Audio API

-- metadata
-- date: 2023-08-29 20:16:44
-- id: 2ugi4q3u
-- site: aws
-- type: post
-- status: published