Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code:

<template>
    <div id="player">
        <div>{{ currentTime }}</div>
        <button @click="start">play</button>
        <div>{{ sequence }}</div>
    </div>
</template>
<script>

 var audioContext = new AudioContext()

 function getRandomInt(min, max) {
     min = Math.ceil(min);
     max = Math.floor(max);
     return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
 }

 export default {
     name: 'player',
     data: function(){
         return {
             sequence: [],
             toRecall: null,
             frequencies: [110, 220, 440, 880],
             lives: 3,
             n: 2,
             currentTime: null,
             stop: false
         }
     },
     methods: {

         playNote: function(startTime, delay, duration){
             var self=this
             return new Promise(function(accept, reject){
                 var pitch = getRandomInt(-12, 13)

                 self.sequence.push(pitch)
                 var startTime = audioContext.currentTime + delay
                 var endTime = startTime + duration
                 var oscillator = audioContext.createOscillator()
                 oscillator.connect(audioContext.destination)
                 oscillator.type = 'sawtooth'
                 oscillator.start(startTime)
                 oscillator.stop(endTime)
                 accept()
             })                          
         },
         start: function(){
             var self=this
             this.currentTime = audioContext.currentTime
             this.playNote(0, 0, 1).then(function(){
                 // do once the note is done playing
                 self.sequence.pop()
             })
         }
     }
 }

I am aiming to have the sequence of pitches (currently just one) displayed on screen for the duration that the note plays, then vanish - indicating that pop is triggered only after the note has finished playing. Any help with this issue would be greatly appreciated. Thank you.

Answer №1

To get more information, check out this link regarding OscillatorNode as an AudioScheduledSourceNode. You can utilize the following script to handle the end event:


oscillator.onended = function() {
  /* Perform actions like removing notes from display */
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with file upload: The view is not refreshing in response to non-angular events

I am having an issue with my upload component where the view is not updating when the onchange event fires. Even though I can see the file names being logged, nothing is happening on the screen. My approach involves using a directive so that I can easily ...

Using JavaScript regular expressions to validate currency without relying on jQuery

Looking for a solution to create a money mask for an input field without using jquery in my application. Is it possible to achieve this using regular expressions with 'on key up' events, for example? Below is the code snippet: <tr> & ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

The AJAX call was successful with a return code of 200, however an error

HTML code snippet: <a href="javascript:void(0)" onclick="$.join_group(<?=$USER_ID?>, <?=$groups[$i]["id"]?>)"><?=$language["join"]?></a> JavaScript function: $.join_group = function(user_id, group_id) { var input = "u ...

Attempting to evenly distribute items within a div container

My goal is to arrange the items in the container div evenly on a single line. I want them to be spaced out like this: I'm struggling to achieve this layout where the items are on the same line and evenly distributed within the available space. This ...

I am interested in creating a ranking system in JavaScript using JSON data based on points

I have a desire to create the following: var users = {jhon: {name: 'jhon', points: 30}, markus:{name: 'Markus', points: 20}}; // I want it to return like this 1. Jhon with number of points: 30 // 2. Markus with number of points: 20 ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

How to extract the complete URL from the API endpoint in nextjs

I'm curious if there is a way to fetch the complete URL of the current request within the API route (pages/api/myapi). The only response I have found that comes close to what I need is the req.headers.referer, but I am uncertain if this value will alw ...

Is it necessary to perform a specific action if the text within a div matches pre

I've been struggling to make this work properly. Even after removing the AJAX POST function, the issue persists. No alerts or any indication of what's going wrong. Check out the code on JSFiddle: HTML <div class="notification"> ...

Creating a model with a many-to-many association using Sequelize

Technologies Stack: NodeJs, PostgreSQL, Sequelize, Express. I am working with two linked models (User and Role) through the intermediary table User_Roles. While creating a new user using Sequelize.create(), I need to populate the User_Roles table to specif ...

What steps should I take to ensure axios is returning the appropriate buffer type?

Upon initially posting this question, I was completely lost on where to even begin or how to appropriately title it. With the assistance of multiple comments, I enhanced the data provided and finally settled on the current question title - a big thank you ...

Unable to retrieve element using getElementById with dynamically assigned id

After researching on Google and browsing through various Stack Overflow questions (such as this & this), I have not been able to find a solution. I am currently working on validating dynamically generated rows in a table. The loop and alert functions a ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

Issue encountered when trying to render Vue.js file with the view instance "new Vue()"

When working with vue.js and rendering a vue page, I encountered the following error: Error "Cannot GET /KForm" My code in main.js is as follows: import * as componentBase from "@app/app_start" import Form from "@views/Form/Form.vue" import KForm from ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

Using the Object.assign technique will modify the original object's properties in JavaScript

Recently delving into ReactJS, I stumbled upon an interesting revelation regarding the Object.assign() method: const B = { k1: 'b', k2: 'bb', treedata: [{ children: ['g'] }] } var A = Object.assign( ...

What are the steps for implementing async.applyEachSeries in a Node.js application?

I would greatly value it if someone could provide a detailed example illustrating the utilization of the async.applyEachSeries function. async.applyEach([performTask1, performTask2], 'parameter', callback); // here is an example of partial appl ...

The model fails to bind when JSON is sent to the MVC controller

I've been facing an issue with my JSON payload not getting binded in my controller. I attempted creating a class with List<Models.UpdateChatRequestModel> Chats, but that didn't work for me. I also tried using an array name, but that approac ...

What is the process for incorporating the 'url-regex' npm package into an Angular(2/4) project?

I'm currently working on a project with Angular 4 and I've run into some issues while trying to use the url-regex package within my Component. After some troubleshooting, I discovered that this approach seems to work: import * as urlRegex from ...

jQuery Issue DetectedSlight complication spotted with jQuery

I've encountered a peculiar problem with jQuery's contains function: HTML <span class="tag diaTags label label-info">Teststring<span data-role="remove"></span></span> JS When I directly use $('span.diaTags:contai ...