PCM音频实时播放:音频字节数组(16/8位)转为PCM ArrayBuffer流_实时播放pcm数据流-程序员宅基地

技术标签: 音视频  前端  js  pcm  

转载

类型化数组是建立在ArrayBuffer对象的基础上的。它的作用是,分配一段可以存放数据的连续内存区域。

var buf = new ArrayBuffer(32); //生成一段32字节的内存区域,即变量buf在内存中占了32字节大小
ArrayBuffer对象的byteLength属性,返回所分配的内存区域的字节长度。
buf.byteLength //32

ArrayBuffer作为内存区域,可以存放多种类型的数据。不同数据有不同的存储方式,这就叫做“视图”。目前,JavaScript提供以下类型的视图
Int8Array:8位有符号整数,长度1个字节。
Uint8Array:8位无符号整数,长度1个字节。
Int16Array:16位有符号整数,长度2个字节。
Uint16Array:16位无符号整数,长度2个字节。
Int32Array:32位有符号整数,长度4个字节。
Uint32Array:32位无符号整数,长度4个字节。
Float32Array:32位浮点数,长度4个字节。
Float64Array:64位浮点数,长度8个字节。

// audioArr  pcm字节数组(16位)Int8类型   每两位数字代表一个字节  [11,11,22,33] => 代表两个字节
// Int8 => Int16  每两位合成一位  低位 + 高位 * 256
var arraybuffer = new Int8Array(audioArr)
var arraybuffer1 = new Int16Array(data.msgdata.audio.length / 2)
arraybuffer1 = arraybuffer1.map((item, index) => arraybuffer[index * 2] + arraybuffer[index * 2 + 1] * 256)
this.player.feed(arraybuffer1.buffer)
//  audioArr  pcm字节数组(8位) 每一位数字代表一个字节  [11,11,22,33] => 代表四个字节
// 第一步: audio: int8数-128~127 ***转化***  uint8数0~255 (低位转高位:正数不变:127 => 127,负数加255:-1 => 255   -128 => 128)
// 第二步: uint8数0~255 ***映射*** int16数  映射方法为:先减去 128 再乘以 256    0 => -128 => -32768     128 => 0 => 0    255 => 127 => 32512
// 转化:   uint8 转化为 int16   -128 => -32768   0 => 0        127 => 32512
// 映射:   uint8 映射为 int16                    0 => -32768   128 => 0         255 => 32512
var arraybuffer2 = new Uint8Array(audioArr)
var arraybuffer3 = new Int16Array(data.msgdata.audio.length)
arraybuffer3 = arraybuffer3.map((item, index) => 32768 / 128 * (arraybuffer2[index] - 128))
this.player.feed(arraybuffer3.buffer)

创建PCMPlayer

this.player = createPCMPlayer({
    
   inputCodec: 'Int16',
   channels: data.channels,
   sampleRate: data.rate, // 采样率 单位Hz
   flushTime: 200,
})

PCM插件地址

class Player {
    
  constructor(option) {
    
    this.init(option)
  }

  init(option) {
    
    const defaultOption = {
    
      inputCodec: 'Int16', // 传入的数据是采用多少位编码,默认16位
      channels: 1, // 声道数
      sampleRate: 8000, // 采样率 单位Hz
      flushTime: 1000, // 缓存时间 单位 ms
    }

    this.option = Object.assign({
    }, defaultOption, option) // 实例最终配置参数
    this.samples = new Float32Array() // 样本存放区域
    this.interval = setInterval(this.flush.bind(this), this.option.flushTime)
    this.convertValue = this.getConvertValue()
    this.typedArray = this.getTypedArray()
    this.initAudioContext()
    this.bindAudioContextEvent()
  }

  getConvertValue() {
    
    // 根据传入的目标编码位数
    // 选定转换数据所需要的基本值
    const inputCodecs = {
    
      Int8: 128,
      Int16: 32768,
      Int32: 2147483648,
      Float32: 1,
    }
    if (!inputCodecs[this.option.inputCodec]) {
    
      throw new Error(
        'wrong codec.please input one of these codecs:Int8,Int16,Int32,Float32'
      )
    }
    return inputCodecs[this.option.inputCodec]
  }

  getTypedArray() {
    
    // 根据传入的目标编码位数
    // 选定前端的所需要的保存的二进制数据格式
    // 完整TypedArray请看文档
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
    const typedArrays = {
    
      Int8: Int8Array,
      Int16: Int16Array,
      Int32: Int32Array,
      Float32: Float32Array,
    }
    if (!typedArrays[this.option.inputCodec]) {
    
      throw new Error(
        'wrong codec.please input one of these codecs:Int8,Int16,Int32,Float32'
      )
    }
    return typedArrays[this.option.inputCodec]
  }

  initAudioContext() {
    
    // 初始化音频上下文的东西
    this.audioCtx = new (window.AudioContext || window.webkitAudioContext)()
    // 控制音量的 GainNode
    // https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createGain
    this.gainNode = this.audioCtx.createGain()
    this.gainNode.gain.value = 1
    this.gainNode.connect(this.audioCtx.destination)
    this.startTime = this.audioCtx.currentTime
  }

  static isTypedArray(data) {
    
    // 检测输入的数据是否为 TypedArray 类型或 ArrayBuffer 类型
    return (
      (data.byteLength &&
        data.buffer &&
        data.buffer.constructor == ArrayBuffer) ||
      data.constructor == ArrayBuffer
    )
  }

  isSupported(data) {
    
    // 数据类型是否支持
    // 目前支持 ArrayBuffer 或者 TypedArray
    if (!Player.isTypedArray(data)) {
     throw new Error('请传入ArrayBuffer或者任意TypedArray') }
    return true
  }

  // 将获取的数据不断累加到 samples 样本存放区域
  feed(data) {
    
    this.isSupported(data)

    // 获取格式化后的buffer
    data = this.getFormatedValue(data)
    // 开始拷贝buffer数据
    // 新建一个Float32Array的空间, 包含 samples 和传入的 data
    const tmp = new Float32Array(this.samples.length + data.length)
    // 复制当前的实例的buffer值(历史buff)
    // 从头(0)开始复制
    tmp.set(this.samples, 0)
    // 复制传入的新数据
    // 从历史buff位置开始
    tmp.set(data, this.samples.length)
    // 将新的完整buff数据赋值给samples
    // interval定时器也会从samples里面播放数据
    this.samples = tmp
    // console.log('this.samples', this.samples)
  }

  getFormatedValue(data) {
    
    if (data.constructor == ArrayBuffer) {
    
      data = new this.typedArray(data)
    } else {
    
      data = new this.typedArray(data.buffer)
    }

    const float32 = new Float32Array(data.length)

    for (let i = 0; i < data.length; i++) {
    
      // buffer 缓冲区的数据,需要是IEEE754 里32位的线性PCM,范围从-1到+1
      // 所以对数据进行除法
      // 除以对应的位数范围,得到-1到+1的数据
      // float32[i] = data[i] / 0x8000;
      float32[i] = data[i] / this.convertValue
    }
    return float32
  }

  volume(volume) {
    
    this.gainNode.gain.value = volume
  }

  destroy() {
    
    if (this.interval) {
    
      clearInterval(this.interval)
    }
    this.samples = null
    this.audioCtx.close()
    this.audioCtx = null
  }

  flush() {
    
    if (!this.samples.length) return
    const self = this
    var bufferSource = this.audioCtx.createBufferSource()
    if (typeof this.option.onended === 'function') {
    
      bufferSource.onended = function(event) {
    
        self.option.onended(this, event)
      }
    }
    const length = this.samples.length / this.option.channels
    // createBuffer:创建AudioBuffer对象 channels: 通道数    length: 一个代表 buffer 中的样本帧数的整数   sampleRate: 采样率
    // 持续时间 = length / sampleRate  length: 22050帧   sampleRate:44100Hz  持续时间 = 22050 / 44100 = 0.5s
    const audioBuffer = this.audioCtx.createBuffer(
      this.option.channels,
      length,
      this.option.sampleRate
    )

    for (let channel = 0; channel < this.option.channels; channel++) {
    
      // getChannelData: 返回一个 Float32Array,  其中包含与通道关联的 PCM 数据,通道参数定义
      // 参数: channel: 获取特定通道数据的索引
      const audioData = audioBuffer.getChannelData(channel)
      let offset = channel
      let decrement = 50
      for (let i = 0; i < length; i++) {
    
        audioData[i] = this.samples[offset]
        /* fadein */
        if (i < 50) {
    
          audioData[i] = (audioData[i] * i) / 50
        }
        /* fadeout*/
        if (i >= length - 51) {
    
          audioData[i] = (audioData[i] * decrement--) / 50
        }
        offset += this.option.channels
      }
    }

    if (this.startTime < this.audioCtx.currentTime) {
    
      this.startTime = this.audioCtx.currentTime
    }
    // console.log('start vs current ' + this.startTime + ' vs ' + this.audioCtx.currentTime + ' duration: ' + audioBuffer.duration);
    bufferSource.buffer = audioBuffer
    bufferSource.connect(this.gainNode)
    bufferSource.start(this.startTime)
    this.startTime += audioBuffer.duration
    this.samples = new Float32Array()
  }

  async pause() {
    
    await this.audioCtx.suspend()
  }

  async continue() {
    
    await this.audioCtx.resume()
  }

  bindAudioContextEvent() {
    
    const self = this
    if (typeof self.option.onstatechange === 'function') {
    
      this.audioCtx.onstatechange = function(event) {
    
        self.option.onstatechange(this, event, self.audioCtx.state)
      }
    }
  }
}
export function createPCMPlayer(data) {
    
  var PCMPlayer = new Player(data)
  return PCMPlayer
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ccy607/article/details/126854592

智能推荐

东方财富四千余支股票2023年度上半年收盘价格走势涨跌可视化分析_东方财富电脑版怎么看2023年的股价-程序员宅基地

文章浏览阅读311次。1 网络爬取,资金流向,涨跌额和幅度的爬取等等。2 数据分析,分类处理,批量保存为本地的csv格式。3 调用库资源进行数据分析,处理数据,可视化处理。4 生成涨跌幅度和价格走势随时间的变化曲线。通过python实现的数据分析。5 保存为本地高清图片并批量输出。原始结果已保存到压缩文件。_东方财富电脑版怎么看2023年的股价

Android笔记(一):ViewDragHelper实现底部上滑同时底部下滑_android viewdraghelper 实现负一屏下滑-程序员宅基地

文章浏览阅读1k次。先看看效果图:自定义布局控件:public class DragLayout extends FrameLayout { private int title; //限制上滑后的顶部标题高度大小 private Status mStatus = Status.Open; //默认底部是不上滑的 private View mTopCont_android viewdraghelper 实现负一屏下滑

数字图像处理(第四版)-冈萨雷斯-学习过程的笔记_数字图像处理第四版-程序员宅基地

文章浏览阅读3.2k次,点赞13次,收藏91次。数字图像处理(第四版)的学习笔记,对数字图像成像过程、灰度变换和高斯等空间滤波,彩色图像模型,数学形态学处理、基本的边缘检测算法都进行了描述。_数字图像处理第四版

arcgispro制作gp工具、发布和使用GP服务_pro发布gp服务要登录吗-程序员宅基地

文章浏览阅读2.6k次。需求:在arcgispro使用modelbuilder制作包含相交、汇总统计两个工具功能的gp工具,并且将其发布到portal,并在portal上操作该gp服务效果图:模型工具:链接:https://pan.baidu.com/s/1MKSQpKZP7CVPQNWQDamAPA提取码:md6x具体实现:1、制作gp工具。1)将相交工具和汇总统计工具拖拽到mo..._pro发布gp服务要登录吗

SSMP整合综合案例_风格无涯-程序员宅基地

文章浏览阅读72次。关注itheima谢谢喵_风格无涯

As you develop your lead qualification criteria-程序员宅基地

文章浏览阅读126次。While you have on your own the Christian Louboutin replicas they enable you to definitely present the average pe...

随便推点

nodejs基于vue+微信小程序+python+PHP小型超市进销存管理系统的设计与实现-计算机毕业设计推荐_node 进销存-程序员宅基地

文章浏览阅读80次。小型超市进销存管理系统自然也不例外,互联网技术的日益成熟,推动了小型超市进销存管理系统的建立,从根本上改变了以往的传统管理模式;不但降低了服务管理的难度,还提高了管理的灵活性。小型超市进销存管理系统,主要的模块包括管理员;系统首页、个人中心、采购员管理、业务员管理、仓管员管理、供货商管理、客户信息管理、商品分类管理、仓库库存管理、采购进货管理、销售信息管理、入库信息管理、调拨单管理、出库信息管理、盘点信息管理、账目信息管理,采购员;_node 进销存

Linked List Cycle-- 判断一个单向链表中是否有环存在_linklist里面有一个环-程序员宅基地

文章浏览阅读3.4k次。原题:Given a linked list, determine if it has a cycle in it. =>给定一个单向链表,如何判断它里面是否有环存在。Follow up:Can you solve it without using extra space? =>能否不使用额外的空间来解决这个问题?/** * Definition f_linklist里面有一个环

使用Keil MDK创建STM32标准库工程_mdk stm32新建工程-程序员宅基地

文章浏览阅读684次,点赞29次,收藏35次。使用Keil创建STM32标准库工程_mdk stm32新建工程

如何在Windows下安装 python-magic_python magic 安装-程序员宅基地

文章浏览阅读3.6k次。1.下载编译安装python-magic2. a.下载 file-5.03-setup.exe http://sourceforge.net/projects/gnuwin32/files/file/5.03/b.安装到 C:\GnuWin32c.环境变量Path里添加 C:\GnuWin32\bin_python magic 安装

阿里云弹性计算通用算力型u1实例性能评测,性价比高_通用算力型 u1-程序员宅基地

文章浏览阅读1.1k次,点赞8次,收藏18次。阿里云服务器u1通用算力型Universal实例高性价比,CPU采用2.5 GHz主频的Intel Xeon Platinum 8163(Skylake)或者8269CY(Cascade Lake)处理器,CPU内存比1:1/1:2/1:4/1:8。云服务器u1适用于Web应用及网站,企业办公类应用,数据分析和计算等大多数通用的对vCPU算力和性能要求不高的应用场景。阿里云通用算力型u1云服务器。_通用算力型 u1

【打印机】argox入门_argoxprintservice-程序员宅基地

文章浏览阅读3.2k次。立象dx4300打印机调试。1 环境搭建1.1 登录http://www.argox.com.cn/Pages/servicedownload.aspx下载驱动和手册。1.2 安装正常安装即可,电脑要先接上打印机的USB口。1.3 通过USB连接打印机,打开Printer Tool工具。如果没有检测到打印机,可能是驱动安装有问题。1.4 获取打印机的参数可以看到IP..._argoxprintservice