zhongyangxun / audio-recorder

录音 Demo, 实现了声音波形显示,录音文件下载。

Home Page:https://zhongyangxun.github.io/audio-recorder/dist

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Audio Recorder

A audio-record demo, with recording audio wave and playing audio wave.

Experience it online

click me

How to run

Install Parcel:

npm install -g parcel-bundler

Go to the demo root folder and install dependencies:

npm install

Run:

npm start

Visit http://localhost:1234/.

Build:

npm run build

Detail

Record

Using Recorder lib to record audio.

Initiate:

const rec = Recorder({
  type: "mp3",
  sampleRate: 16000,
  bitRate: 16
});

Start:

rec.open(function () {
  rec.start();
});

Stop and process audio data:

rec.stop(function (blob) {
  rec.close();
  // Show audio wave.
  loadWave(blob);
  // Enable audio download. 
  enableDownload(blob);
}, function () {
  console.log('Record failed');
});

Wave

The audio wave is generated with Wavesurfer.js.

HTML code:

<!-- Wave container -->
<div id="waveform"></div>

<script src="https://unpkg.com/wavesurfer.js"></script>
<!-- Microphone plugin for recording wave -->
<script src="https://unpkg.com/wavesurfer.js/dist/plugin/wavesurfer.microphone.min.js"></script>

Initiate:

const wavesurfer = WaveSurfer.create({
  container: '#waveform',
  waveColor: 'violet',
  progressColor: 'purple',
  cursorColor: 'white',
  plugins: [
    // Using microphone plugin to create wave when recording.
    WaveSurfer.microphone.create()
  ]
});

Generate playing wave with load method and ObjectURL:

function loadWave(blob) {
  objectURL = URL.createObjectURL(blob);
  wavesurfer.load(objectURL);
}

Recording wave is created by microphone plugin of WaveSurfer.js, when the start method below is success, the wave is generated.

wavesurfer.microphone.start();

Download

HTML:

<button class="btn btn-download" id="downloadButton" disabled>
  Download
  <a href="#" class="download-link" id="download-link" download></a>
</button>

Style (Hide the a tag when download button was disabled):

.btn-download {
  position: relative;

  &:disabled {
    a {
      display: none;
    }
  }

  a {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
}

JavaScript:

function enableDownload(blob) {
  const downloadLinkEl = document.getElementById('download-link');
  const fileName = new Date().toLocaleString() + 'mp3';
  downloadLinkEl.href = URL.createObjectURL(blob);
  downloadLinkEl.download = fileName;

  downloadButton.disabled = false;
}

About

录音 Demo, 实现了声音波形显示,录音文件下载。

https://zhongyangxun.github.io/audio-recorder/dist


Languages

Language:JavaScript 67.4%Language:HTML 19.1%Language:SCSS 13.5%