uil

Building practices for the future

Sacred Groves in Auroville is being built using ecologically sensitive construction methods and material.




uil

How green is my building

In the wake of the conference on building sustainability, architect Minni Sastry of TERI speaks to RANJANI GOVIND on the emerging thoughts relevant to the industry




uil

Building digital trust with quantum tech

QNu Labs devises qubit-powered solutions for the ‘trillion-dollar cyber-attack problem’ 




uil

‘Focused on building a high-conviction portfolio’

How fund house Cactus Partners ensures its capital goes toward growth rather than just keeping operations running




uil

Building up an Arsenal

The autobiography of a coach who revolutionised English football




uil

Building digital platforms

A book on digital players in the post-pandemic world




uil

Building your personal brand

Your brand is also about how the world perceives you




uil

T.N. CM Stalin inaugurates new buildings for rural local bodies




uil

Building a Dictaphone Using Media Recorder and getUserMedia

Chris Mills brushes up his shorthand and shows how the MediaStream Recording API in modern browsers can be used to capture audio directly from the user’s device. Inching ever closer to the capabilities of native software, it truly is an exciting time to be a web developer.


The MediaStream Recording API makes it easy to record audio and/or video streams. When used with MediaDevices.getUserMedia(), it provides an easy way to record media from the user’s input devices and instantly use the result in web apps. This article shows how to use these technologies to create a fun dictaphone app.

A sample application: Web Dictaphone

To demonstrate basic usage of the MediaRecorder API, we have built a web-based dictaphone. It allows you to record snippets of audio and then play them back. It even gives you a visualisation of your device’s sound input, using the Web Audio API. We’ll just concentrate on the recording and playback functionality in this article, for brevity’s sake.

You can see this demo running live, or grab the source code on GitHub. This has pretty good support on modern desktop browsers, but pretty patchy support on mobile browsers currently.

Basic app setup

To grab the media stream we want to capture, we use getUserMedia(). We then use the MediaRecorder API to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back.

We’ll first declare some variables for the record and stop buttons, and the <article> that will contain the generated audio players:

const record = document.querySelector('.record');
const stop = document.querySelector('.stop');
const soundClips = document.querySelector('.sound-clips');

Next, we set up the basic getUserMedia structure:

if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
   console.log('getUserMedia supported.');
   navigator.mediaDevices.getUserMedia (
      // constraints - only audio needed for this app
      {
         audio: true
      })

      // Success callback
      .then(function(stream) {

      })

      // Error callback
      .catch(function(err) {
         console.log('The following `getUserMedia` error occured: ' + err);
      }
   );
} else {
   console.log('getUserMedia not supported on your browser!');
}

The whole thing is wrapped in a test that checks whether getUserMedia is supported before running anything else. Next, we call getUserMedia() and inside it define:

  • The constraints: Only audio is to be captured for our dictaphone.
  • The success callback: This code is run once the getUserMedia call has been completed successfully.
  • The error/failure callback: The code is run if the getUserMedia call fails for whatever reason.

Note: All of the code below is found inside the getUserMedia success callback in the finished version.

Capturing the media stream

Once getUserMedia has created a media stream successfully, you create a new Media Recorder instance with the MediaRecorder() constructor and pass it the stream directly. This is your entry point into using the MediaRecorder API — the stream is now ready to be captured into a <Blob>, in the default encoding format of your browser.

const mediaRecorder = new MediaRecorder(stream);

There are a series of methods available in the MediaRecorder interface that allow you to control recording of the media stream; in Web Dictaphone we just make use of two, and listen to some events. First of all, MediaRecorder.start() is used to start recording the stream once the record button is pressed:

record.onclick = function() {
  mediaRecorder.start();
  console.log(mediaRecorder.state);
  console.log("recorder started");
  record.style.background = "red";
  record.style.color = "black";
}

When the MediaRecorder is recording, the MediaRecorder.state property will return a value of “recording”.

As recording progresses, we need to collect the audio data. We register an event handler to do this using mediaRecorder.ondataavailable:

let chunks = [];

mediaRecorder.ondataavailable = function(e) {
  chunks.push(e.data);
}

Last, we use the MediaRecorder.stop() method to stop the recording when the stop button is pressed, and finalize the Blob ready for use somewhere else in our application.

stop.onclick = function() {
  mediaRecorder.stop();
  console.log(mediaRecorder.state);
  console.log("recorder stopped");
  record.style.background = "";
  record.style.color = "";
}

Note that the recording may also stop naturally if the media stream ends (e.g. if you were grabbing a song track and the track ended, or the user stopped sharing their microphone).

Grabbing and using the blob

When recording has stopped, the state property returns a value of “inactive”, and a stop event is fired. We register an event handler for this using mediaRecorder.onstop, and construct our blob there from all the chunks we have received:

mediaRecorder.onstop = function(e) {
  console.log("recorder stopped");

  const clipName = prompt('Enter a name for your sound clip');

  const clipContainer = document.createElement('article');
  const clipLabel = document.createElement('p');
  const audio = document.createElement('audio');
  const deleteButton = document.createElement('button');

  clipContainer.classList.add('clip');
  audio.setAttribute('controls', '');
  deleteButton.innerHTML = "Delete";
  clipLabel.innerHTML = clipName;

  clipContainer.appendChild(audio);
  clipContainer.appendChild(clipLabel);
  clipContainer.appendChild(deleteButton);
  soundClips.appendChild(clipContainer);

  const blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
  chunks = [];
  const audioURL = window.URL.createObjectURL(blob);
  audio.src = audioURL;

  deleteButton.onclick = function(e) {
    let evtTgt = e.target;
    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
  }
}

Let’s go through the above code and look at what’s happening.

First, we display a prompt asking the user to name their clip.

Next, we create an HTML structure like the following, inserting it into our clip container, which is an <article> element.

<article class="clip">
  <audio controls></audio>
  <p>_your clip name_</p>
  <button>Delete</button>
</article>

After that, we create a combined Blob out of the recorded audio chunks, and create an object URL pointing to it, using window.URL.createObjectURL(blob). We then set the value of the <audio> element’s src attribute to the object URL, so that when the play button is pressed on the audio player, it will play the Blob.

Finally, we set an onclick handler on the delete button to be a function that deletes the whole clip HTML structure.

So that’s basically it — we have a rough and ready dictaphone. Have fun recording those Christmas jingles! As a reminder, you can find the source code, and see it running live, on the MDN GitHub.


This article is based on Using the MediaStream Recording API by Mozilla Contributors, and is licensed under CC-BY-SA 2.5.


About the author

Chris Mills manages the MDN web docs writers’ team at Mozilla, which involves spreadsheets, meetings, writing docs and demos about open web technologies, and occasional tech talks at conferences and universities. He used to work for Opera and W3C, and enjoys playing heavy metal drums and drinking good beer.

More articles by Chris




uil

Building a ‘perfect meal’

Is it possible to have that balanced meal with the right amount of protein, starch and veggies? Read on and find out.




uil

Reflections on Practice : Relationship Building / directed by: Nettie Wild ; production agencies: National Film Board of Canada (Montreal), British Columbia Centre for Disease Control. Street Nurse Program (Vancouver)

Montreal : National Film Board of Canada, 2019




uil

Naidu sets June deadline for completion of new terminal building at Vijayawada airport

Chief Minister suggests changes in the design of the expansion works to reflect Andhra Pradesh’s culture and heritage




uil

Wavelets in soft computing [electronic resource] / Marc Thuillard

Hackensack, NJ : World Scientific Publishing Co. Pte. Ltd., [2023]




uil

Storm building in the Bay of Bengal?

Most forecasting agencies indicate the possibility of a storm building in the Southwest Bay of Bengal, just ahead of the onset of Southwest monsoon in these parts. What it holds for onset dynamics over mainland India has crucial signifcance for onward progress of seasonal rains.




uil

Arihant partners with Empee Hotels to build new commercial space in Chennai

This project will integrate office space with hospitality services, says a release




uil

Rising costs make urban affordable houses unviable for builders

Government’s PM Awas Yojana faces challenges due to rising land prices, construction costs, and pricing limitations for builders




uil

Mindspace REIT to build 3 data centres for Princeton Digital Group

The REIT has already developed two data centers for PDG with an area of 6.3 lakh square feet and the current contract will add 10 lakh square feet to its portfolio




uil

Poulomi Estates to build ₹800-crore residential project in Bengaluru

The project will have a total of 850 apartments, which are in the range of 1,450 sq ft to 2,550 sq ft




uil

Brigade Enterprises to build a high-rise residential project at Perambur by investing ₹620 crore

It acquired the land from PVP ventures




uil

Godrej Properties acquires six land parcels in Jul-Sep to build projects worth ₹9,650 crore

Godrej Properties’ business development additions of ₹12,650 crore in April-September ensure a strong launch pipeline for years to come, says company’s MD & CEO Gaurav Pandey




uil

October home sales soar in Mumbai; Builders to keep the frenzy going

According to state government data, it has garnered revenue of over ₹1,200 crore as stamp duty from the city alone




uil

Sattva Group plans ₹14,000-crore investment to build 80 m sft of residential, commercial projects

Co-living space a focus area for Sattva Group, eyes co-living capacity of 15-16,000 beds by year-end




uil

DLF to invest ₹8,000 cr to build super-luxury project in Gurugram

The company will develop around 420 apartments in this project




uil

Interarch Building Products plans to double turnover to ₹2,500 cr by 2028

The company, which got listed recently, clocked a turnover of ₹1,293 crore in FY24




uil

HYDRAA created fear among encroachers and big builders and not common people: Telangana CM




uil

The building and breaching of Fortress India: chronicling a cycle of cricket dominance

India was invincible at home for 12 years, winning 18 consecutive Test series before New Zealand snapped the record streak in a historic clean sweep. What went into the making of the unbeaten run, what are the consequences of defeat and what does the future look like?




uil

Gujarat HC asks why illegal building in Rajkot game zone was not demolished for a year

‘Demolition order proves that officials knew the structure was illegal,’ the Chief Justice said




uil

Visva-Bharati teaches young volunteers how to preserve old buildings

Visva-Bharati is concluding a two-week workshop called Heritage Awareness Camp




uil

Neeraj Chopra set to resume Olympic build-up at Paavo Nurmi Games in Finland

The 26-year-old superstar, the lone Indian in the field, will be up against German teenaged sensation Max Dehning, who is the youngest member of the coveted 90m club, which Chopra is aspiring to enter.




uil

India building up gold reserves, says Das

Per official data, the value of gold in the forex reserves stood at $51.487 billion as on March 22, which is $6.287 billion higher than the value as at end-March 2023




uil

RBI steadily building up gold reserves

The RBI held about 60 per cent of its gold reserves in safe custody in India as at September-end 2024 against about 50 per cent as at March-end 2024




uil

Molecular Fe(II)–Ln(III) dyads for luminescence reading of spin-state equilibria at the molecular level

Dalton Trans., 2024, 53,17756-17765
DOI: 10.1039/D4DT01868K, Frontier
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Timothée Lathion, Neel Deorukhkar, Charlotte Egger, Homayoun Nozary, Claude Piguet
Efficient and easy lanthanide(III)-based luminescence reading of iron(II) spin-state equilibria presents an attractive challenge, owing to the delicate combination of the primogenic effect and the Fermi golden rule.
The content of this RSS Feed (c) The Royal Society of Chemistry




uil

Building mental reserves

Treat mental health like an “account” with regular deposits of nurturing habits, thoughts, and actions




uil

Inquilab and Endurance catch the eye




uil

Atal tunnel builder Afcon Infrastructure to raise ₹5,430 crore via IPO on October 25

Afcon Infrastructure plans to use ₹600 crore for repaying debt, ₹320 crore for funding long-term working capital requirements and ₹80 crore for buying construction equipment.  




uil

Megha Engineering to build Young India Skills University in Hyderabad with ₹200 crore under CSR

The Chief Minister performed ‘Bhumi Puja’ for the construction of the Skill University on 57 acres of land near Meerkhanpet in Kandukur mandal in August this year




uil

Shaping a new generation of green builders

With climate change and the demand to create a responsible and adaptive built environment, is sustainability given enough importance in the classroom?




uil

Will build presence in the South: Nitin Gadkari

In an interview with The Hindu, Mr. Gadkari said the BJP remains united in its ideological commitment, with no discord between the party and the RSS.



  • Lok Sabha Elections

uil

Scoop: Was Prince Andrew Really Guilty?

Scoop seems like they conclude he is but Vaihayasi Pande Daniel recommends that you watch the film to find out for yourselves.




uil

Constructing Nickel Complex/Crystalline Carbon Nitride Hybrid with a Built-in Electric Field for Boosting CO2 Photoreduction

Nanoscale, 2024, Accepted Manuscript
DOI: 10.1039/D4NR03586K, Paper
Yanrui Li, Linda Wang, Bo Zhan, Liangqing Zhang, Xiaolin Zhu, Xiang Gao
Sluggish charge separation dynamics resulting from the amorphous structure and the lack of driving force for graphitic carbon nitride (GCN) limits its highly effective CO2 photoreduction performance. Herein, a built-in...
The content of this RSS Feed (c) The Royal Society of Chemistry




uil

‘The question of building stakeholder trust can have more airtime in the boardroom’




uil

Newer building blocks of organisational culture 

O.C. Tanner’s latest report lists out the increasing responsibilities of corporate leaders in building a positive and productive workplace




uil

Camille Saint-Saëns - Le cygne from “Les Carnaval des Animaux” (arr. by Alexandre Guilmant)

Organ sheet music by Camille Saint-Saëns | Le cygne from “Les Carnaval des Animaux” (arr. by Alexandre Guilmant)

Reference: BE01182
Title: Le cygne from “Les Carnaval des Animaux” (arr. by Alexandre Guilmant)
Composer: Camille Saint-Saëns
Instrument: Organ solo
Price: €8.49
Pages: 5
Format: Portrait - 9” x 12” paper-back
Publication Date: 30-Sep-2024
Edition: New
Editor: W. B. Henshaw
EAN/ISMN: 979-0-2067-1182-4




uil

Building your space brick by brick

The writer on why the humble brick scores over the much-cheaper block masonry




uil

HC directs officials to inspect GRH building




uil

CM Stalin inaugurates 13 school buildings in Tenkasi district




uil

Grievances redressal meeting to be held at new Collectorate building in Virudhunagar on Monday




uil

HC directs authorities to file status report on decision taken to demolish dilapidated library building and construct new one

A PIL petition complains about the dilapidated condition of the building and seeks a direction to authorities to construct a new one in its place.




uil

New panchayat union buildings inaugurated at Thoothukudi and Kanniyakumari




uil

Beyond the classroom: When students build start ups

Classroom theories are okay, but when you sit with your group to chill and create something of your own by putting the minds together, you open doors to recognition by major international companies. That’s the true essence of teamwork.