使用Web Audio API实现基于浏览器的Web端录音

本文介绍如何利用Web Audio API在浏览器中实现单声道录音功能。通过两个JavaScript文件,recorder.js和recorderWorker.js,可以创建一个Recorder类来录制、停止和导出WAV格式的音频。录音功能依赖于getUserMedia接口获取音频输入流,并使用AudioContext进行处理。录音文件的采样率为48000Hz,可通过调整代码实现不同采样率的压缩。
摘要由CSDN通过智能技术生成

有时候会有通过Web端录音的需求,那么如何实现呢,通过Web Audio API能够实现,具体可以查看官网的API,下面是实现单声道录音(压缩音频大小)的一个例子,共需要两个js文件,具体如下:

第一个js文件: recorder.js

(function(window){
 
  var WORKER_PATH = 'resources/js/recorderWorker.js'; //自己设置recorderWorker.js的路径
 
  var Recorder = function(source, cfg){
    var config = cfg || {};
    var bufferLen = config.bufferLen || 4096;   
    this.context = source.context;
    this.node = this.context.createScriptProcessor(bufferLen, 1, 1);
    var worker = new Worker(config.workerPath || WORKER_PATH);
    worker.postMessage({
      command: 'init',
      config: {
        sampleRate: this.context.sampleRate //默认的是48000
      //sampleRate:11025
      }
    });
    var recording = false,
      currCallback;
 
    this.node.onaudioprocess = function(e){
      if (!recording) return;
      worker.postMessage({
        command: 'record',
        buffer: [
          e.inputBuffer.getChannelData(0)
          //e.inputBuffer.getChannelData(1)
        ]
      });
    }
 
    this.configure = function(cfg){
      for (var prop in cfg){
        if (cfg.hasOwnProperty(prop)){
          config[prop] = cfg[prop];
        }
      }
    }
 
    this.record = function(){
      recording = true;
    }
 
    this.stop = function(){
      recording = false;
    }
 
    this.clear = function(){
      worker.postMessage({ command: 'clear' });
    }
 
    this.getBuffer = function(cb) {
      currCallback = cb || config.callback;
      worker.postMessage({ command: 'getBuffer' })
    }
 
    this.exportWAV = function(cb, type){
      currCallback = cb || config.callback;
      type = type

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值