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

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Locate an item based on the `Contains` criterion by utilizing Express and Mongoose

Looking to find items in my collection that have userName containing adm. Expecting 2 results based on having records with userNames like admin0 and admin2, but the search returns nothing. The query being used is: Person .find({ userName: { $in: &a ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

In-line Vertical Ticker Display

I attempted to use vTicker, but I found that it does not function properly when used as an inline element. <h1> <div id="vticker"><ul>...</ul></div> Some other headline text </h1> My goal is to have the vertica ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

"An issue has been detected in the Entry module, which cannot be located in

My journey into JavaScript is just beginning, as I diligently follow a well-structured node tutorial available on Github. Despite my best efforts in all the modules, I keep encountering an error message whenever I run yarn dev:wds. ERROR in Entry modu ...

Sending the image's identification number as a parameter to a function and showing the total number

On a static page, I have the following HTML markup: <div class="middle-content"> <div class="white-div"> <div class="like-buttons"> <img id="1" src="up.png" onclick="onClick(true, this.id)" /> &l ...

Create a graphical representation of network topology using VueJS

I am in the process of creating a network topology diagram using vueJS and v-network-graph library. Here is an example of the current graph I have achieved: https://i.stack.imgur.com/pTrtW.png What I'm looking to do is add icons on each link betwee ...

Retrieve item from sessionStorage Cart

Greetings to the Stack Overflow community! I've often relied on Slack for valuable information and found solutions to many of my questions. However, this time, I'm facing a challenge that has me stumped. While I'm not an expert in JavaScript ...

Utilizing the power of AWS Lambda in conjunction with moment JS to generate unique

My current time zone is GMT+8, and the AWS region I am using is Singapore (ap-southeast-1). I am facing an issue where there are discrepancies in date calculations between my local machine and when I deploy my code on AWS Lambda. My goal is to ensure that ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Tips for concealing code on the client side in vue/nuxt through Server Side Rendering techniques

I need to execute server-side processing without exposing it to the client side. Although I have successfully used either fetch or asyncData for state population, I want to keep the process hidden from the browser. Here's an example: <template> ...

Travis-CI build encountering errors, however, local tests and builds run smoothly

I'm encountering difficulties getting my unit test to pass with Travis. When running the tests locally, I don't see any errors (unit/e2e)... If you'd like to see the log file, it can be found here in the Travis build log There are numerous ...

When JSON contains slashes, JSON.parse will trigger an error

I am struggling with a valid JSON generated using PHP like this: var json = <?php echo json_encode(['somearray']); ?>. Inside the array, there is an HTML string as shown below: $myArray = ['image' => '<img src="/img/f ...

Tips for transferring a Vuex-stored value to a variable within Vuejs 3 (Quasar 2)

Currently, I have a Vuex store where I am storing a date (referred to as date). In my Vue.js template (using Quasar 2 beta 12), I can easily access this date using {{ date }}. If I make changes to the date in the store, it reflects immediately in the {{ ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...