本文主要是介绍ArrayBuffer内存格式相互转换 ArrayBuffer转化16进制 16进制转字符串 pcm转wav音频,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一: pcm转wav音频
针对于音频格式的转换
const encodeWAV = (samples, numChannels, sampleRate) => {var buffer = new ArrayBuffer(44 + samples.byteLength)var view = new DataView(buffer)/* RIFF identifier */writeString(view, 0, 'RIFF')/* RIFF chunk length */view.setUint32(4, 36 + samples.byteLength, true)/* RIFF type */writeString(view, 8, 'WAVE')/* format chunk identifier */writeString(view, 12, 'fmt ')/* format chunk length */view.setUint32(16, 16, true)/* sample format (raw) */view.setUint16(20, 1, true)/* channel count */view.setUint16(22, numChannels, true)/* sample rate */view.setUint32(24, sampleRate, true)/* byte rate (sample rate * block align) */view.setUint32(28, sampleRate * 4, true)/* block align (channel count * bytes per sample) */view.setUint16(32, numChannels * 2, true)/* bits per sample */view.setUint16(34, 16, true)/* data chunk identifier */writeString(view, 36, 'data')/* data chunk length */view.setUint32(40, samples.byteLength, true)copyBytes(view, 44, samples)return view
}
const copyBytes = (output, offset, input) => {const dataView = new DataView(input)for (var i = 0; i < input.byteLength; i++, offset++) {output.setInt8(offset, dataView.getInt8(i))}
}
const writeString = (view, offset, string) => {for (var i = 0; i < string.length; i++) {view.setUint8(offset + i, string.charCodeAt(i))}
}
二: ArrayBuffer转16进制
const buf2hex = (arrayBuffer) => {let hex = ''let uint8Array = new Uint8Array(arrayBuffer)for (let i = 0; i < uint8Array.length; i++) {// 将字节转换为16进制字符串,并添加到hex中hex += uint8Array[i].toString(16).padStart(2, '0') // 使用padStart确保总是两位数}return hex
}
三:16进制转字符串
const hexToString = (str: any) => {var val = '',len = str.length / 2for (var i = 0; i < len; i++) {val += String.fromCharCode(parseInt(str.substr(i * 2, 2), 16))}return utf8to16(val)
}
//处理中文乱码问题
const utf8to16 = (str) => {var out, i, len, cvar char2, char3out = ''len = str.lengthi = 0while (i < len) {c = str.charCodeAt(i++)switch (c >> 4) {case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:out += str.charAt(i - 1)breakcase 12:case 13:char2 = str.charCodeAt(i++)out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f))breakcase 14:char2 = str.charCodeAt(i++)char3 = str.charCodeAt(i++)out += String.fromCharCode(((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0))break}}return out
}
四:ArrayBuffer转base64
如果在小程序中使用 需引入 base64js.js
const toBase64 = (buffer : any, type) => {
var binary = ''var bytes = new Uint8Array(buffer)var len = bytes.byteLengthfor (var i = 0; i < len; i++) {binary += String.fromCharCode(bytes[i])}return window.btoa(binary)
}
这篇关于ArrayBuffer内存格式相互转换 ArrayBuffer转化16进制 16进制转字符串 pcm转wav音频的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!