类型化数组是建立在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,
})
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
}
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作
我使用Ember作为我的前端和GrapeAPI来为我的API提供服务。前端发送类似:{"service"=>{"name"=>"Name","duration"=>"30","user"=>nil,"organization"=>"org","category"=>nil,"description"=>"description","disabled"=>true,"color"=>nil,"availabilities"=>[{"day"=>"Saturday","enabled"=>false,"timeSlots"=>[{"startAt"=>"09:00AM","endAt"=>
我正在尝试按0-9和a-z的顺序创建数字和字母列表。我有一组值value_array=['0','1','2','3','4','5','6','7','8','9','a','b','光盘','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','','u','v','w','x','y','z']和一个组合列表的数组,按顺序,这些数字可以产生x个字符,比方说三个list_array=[]和一个当前字母和数字组合的数组(在将它插入列表数组之前我会把它变成一个字符串,]current_combo['0','0','0']
查看我的Ruby代码:h=Hash.new([])h[0]=:word1h[1]=h[1]输出是:Hash={0=>:word1,1=>[:word2,:word3],2=>[:word2,:word3]}我希望有Hash={0=>:word1,1=>[:word2],2=>[:word3]}为什么要附加第二个哈希元素(数组)?如何将新数组元素附加到第三个哈希元素? 最佳答案 如果您提供单个值作为Hash.new的参数(例如Hash.new([]),完全相同的对象将用作每个缺失键的默认值。这就是您所拥有的,那是你不想要的。您可以改用