Is there a way to play back the recorded sound in my JavaScript project?

I recently completed a tutorial on audio recording in JavaScript where an array is used to store the recorded audio and convert it into a URL for playback. The setup includes a button with a function that both records and automatically plays the audio when clicked. However, I am now looking to add a second button that will only play the audio when pressed, rather than playing automatically after recording. How can I achieve this using plain JavaScript?

Any help or guidance would be greatly appreciated.

function setup() {
  createCanvas(400, 400);
  button = createButton('Audio Hack');
  button.position(160, 180);
  button.mousePressed(audioHack);
  }

function audioHack() {
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then(stream => {
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.start();

      const audioChunks = [];
      mediaRecorder.addEventListener("dataavailable", event => {
        audioChunks.push(event.data);
      });

      mediaRecorder.addEventListener("stop", () => {
        const audioBlob = new Blob(audioChunks);
        const audioUrl = URL.createObjectURL(audioBlob);
        const audio = new Audio(audioUrl);
        audio.play();
      });

      setTimeout(() => {
        mediaRecorder.stop();
      }, 3000);
    });
}

Answer №1

One way to achieve this task is by storing the audio in a global variable and removing the audio.play(). A great alternative solution is using the p5.sound library from p5.js. Check out the documentation here:

let recorderAudio = null;    

function setup() {
  createCanvas(400, 400);
  button = createButton('Audio Hack');
  button.position(160, 180);
  button.mousePressed(audioHack);

  playButton = createButton('Play Audio');
  playButton.position(160, 200);
  playButton.mousePressed(function(){
    if (recordedAudio != null) recordedAudio.play();
  });
}

function audioHack() {
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then(stream => {
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.start();

      const audioChunks = [];
      mediaRecorder.addEventListener("dataavailable", event => {
        audioChunks.push(event.data);
      });

      mediaRecorder.addEventListener("stop", () => {
        const audioBlob = new Blob(audioChunks);
        const audioUrl = URL.createObjectURL(audioBlob);
        recordedAudio = new Audio(audioUrl);
        //audio.play();
      });

      setTimeout(() => {
        mediaRecorder.stop();
      }, 3000);
    });
}

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

Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time. Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I ...

What is the best way to toggle the readonly attribute on an input within an ng-repeat row when a button is clicked?

Here is some HTML content: <!---- HTML Content ----> <div class="container-fluid" ng-app="myApp"><br> <div class="row" ng-controller="mainController"> <div class="col-md-12"> <div class="panel pa ...

What is the best way to create quizzes using text inputs instead of the usual multiple choice options in HTML, while still being able to determine which answers are correct or incorrect?

For my school project, I am in desperate need of help! Unfortunately, coding is not my forte and I am stuck with nothing to fill in here. Your assistance would be greatly appreciated. Thanks in advance! ...

Is there a way to display a Google Map marker after a certain amount of time without needing to refresh the

Is it possible to update Google Map markers without refreshing the map itself every 30 seconds? The markers' latitudes and longitudes are retrieved from a database. Once obtained, these markers are then allocated onto the Google Map. However, the i ...

Creating an AJAX function to display a popup window for users who are already registered - here's how!

I am currently working on a dropwizard-java project. Whenever users click the subscribe button, it displays a thank you message for subscribing and then checks if the user is already registered. I would like to have a pop-up window immediately show whethe ...

Encountering an error while attempting to utilize the split function in browser.umd.js due to

Hey there, I seem to be encountering an issue that states: Cannot read properties of undefined (reading 'split'). I came across this error message in the console https://i.sstatic.net/3nICv.png Upon clicking the link to the error, it directs me ...

What is the best way to stack a canvas box on top of another canvas box?

My goal is to have two canvas squares stacked on top of each other. While I am familiar with drawing on canvas, I need assistance in placing one canvas on top of another. Despite my attempts at setting the position, I have not been successful. <canvas ...

Is there a way to add a price to an object in JavaScript?

Purchasedata.find(function(err, purchasedatas) { if (err) { return handleError(res, err); } var totalprice = 0; for (var i = 0; i < purchasedatas.length; i++) { findProduct(i, function(i, price) { }); } ...

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...

Obtain a picture from mongodb utilizing gridfs and display it in Ember.js

Working with Ember JS and Sails JS has been smooth sailing when uploading images to a Mongo db using the "gridfs" adapter. The chunks and files records update seamlessly, but now I've hit a roadblock. The issue arises when trying to retrieve the uplo ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Convert an array of objects into an object where the keys are determined by the value of a specific

I'm working with an array that looks like this: const inventory = [ { fruit: 'apple', quality: 'good', quantity: 10 }, { fruit: 'banana', quality: 'average', quantity: 5 }, { fruit: 'orange', qua ...

Using v-model in Vue, the first option has been chosen

Is there a way to set a default value for myselect when a user visits the site for the first time? I want the first option to be selected initially, but allow the user to change their choice if they prefer another option. Can this be achieved using v-model ...

Issue with accessing Vue.js parameter in route

Trying to work with both VueJS and Laravel, I am currently facing an issue where I cannot retrieve a parameter value. Can anyone provide guidance on how to solve this problem? This is my VueJS code: getTestData:function () { let config = { par ...

Changing the state using React's useState hook

Why is it considered a bad idea to directly mutate state when using React's new useState hook? I couldn't find any information on this topic. Let's look at the following code: const [values, setValues] = useState({}) // doSomething can be ...

The ReactJS code encountered an error when attempting to access the 'location' property of an undefined or null reference

My Reactapp is encountering an error due to a specific file. import React from 'react'; import { Router, Route } from 'react-router'; import App from './components/App'; import About from './components/About'; im ...

Responsive Website with Horizontal Scrolling

Is it feasible to develop a website that smoothly scrolls across five panels horizontally while maintaining responsiveness? I've managed to achieve this for a specific viewport size by nesting a div with the five panels extended and using javascript t ...

Passing an array from PHP to JavaScript using AJAX

Here is the code snippet on the server side: <?php header('Content-Type: text/html; charset=utf-8'); require "../general.variables.php"; require "../functions_validation.php"; require "../functions_general.php"; require "../../db_con.php"; $ ...

Enabling CORs headers in Express continues to lead to errors

I have implemented the CORS code provided on http://enable-cors.org/ for express into my index.js file. /*these first five line direct from http://enable-cors.org/.com*/ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); ...

Reloading a page will display [object CSSStyleDeclaration]

Upon editing content and saving changes, instead of displaying my updated content when refreshing the page, it shows [object CSSStyleDeclaration]. function newElement() { let li = document.createElement("li"); let inputvalue = document.querySelector ...