PCMPlayer播放器的使用教程(添加清理暂存区方法)

2024-09-04 14:20

本文主要是介绍PCMPlayer播放器的使用教程(添加清理暂存区方法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 解决的问题:在我们使用PCMPlayer播放的时候,时间长,即使停止播放了,也会有一段声音,这是因为音频暂存区没有清理 

解决方案:添加一个stop方法,话不多上 直接上代码  复制就能使用 !!!

function PCMPlayer(option) {this.init(option);
}PCMPlayer.prototype.init = function(option) {var defaults = {encoding: '16bitInt',channels: 1,sampleRate: 8000,flushingTime: 1000};this.option = Object.assign({}, defaults, option);this.samples = new Float32Array();this.flush = this.flush.bind(this);this.interval = setInterval(this.flush, this.option.flushingTime);this.maxValue = this.getMaxValue();this.typedArray = this.getTypedArray();this.createContext();
};PCMPlayer.prototype.getMaxValue = function () {var encodings = {'8bitInt': 128,'16bitInt': 32768,'32bitInt': 2147483648,'32bitFloat': 1};return encodings[this.option.encoding] ? encodings[this.option.encoding] : encodings['16bitInt'];
};PCMPlayer.prototype.getTypedArray = function () {var typedArrays = {'8bitInt': Int8Array,'16bitInt': Int16Array,'32bitInt': Int32Array,'32bitFloat': Float32Array};return typedArrays[this.option.encoding] ? typedArrays[this.option.encoding] : typedArrays['16bitInt'];
};PCMPlayer.prototype.createContext = function() {this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();this.gainNode = this.audioCtx.createGain();this.gainNode.gain.value = 1;this.gainNode.connect(this.audioCtx.destination);this.startTime = this.audioCtx.currentTime;
};PCMPlayer.prototype.isTypedArray = function(data) {return (data.byteLength && data.buffer && data.buffer.constructor === ArrayBuffer);
};PCMPlayer.prototype.feed = function(data) {if (!this.isTypedArray(data)) return;const formattedData = this.getFormatedValue(data);var tmp = new Float32Array(this.samples.length + formattedData.length);console.log("缓冲区tmp:" + tmp.length);tmp.set(this.samples, 0);tmp.set(formattedData, this.samples.length);this.samples = tmp;console.log("缓冲区samples:" + this.samples.length);
};PCMPlayer.prototype.getFormatedValue = function(inputData) {var data = new this.typedArray(inputData.buffer),float32 = new Float32Array(data.length),i;for (i = 0; i < data.length; i++) {float32[i] = data[i] / this.maxValue;}return float32;
};PCMPlayer.prototype.volume = function(volume) {this.gainNode.gain.value = volume;
};PCMPlayer.prototype.destroy = function() {if (this.interval) {clearInterval(this.interval);}this.samples = null;this.audioCtx.close();this.audioCtx = null;
};PCMPlayer.prototype.flush = function() {if (!this.samples.length) return;var bufferSource = this.audioCtx.createBufferSource(),length = this.samples.length / this.option.channels,audioBuffer = this.audioCtx.createBuffer(this.option.channels, length, this.option.sampleRate),audioData,channel,offset,i,decrement;for (channel = 0; channel < this.option.channels; channel++) {audioData = audioBuffer.getChannelData(channel);offset = channel;decrement = 50;for (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();
};PCMPlayer.prototype.stop = function() {// 清理所有缓冲区数据this.samples = new Float32Array();// 检查 AudioContext 状态并确保完全关闭if (this.audioCtx && this.audioCtx.state !== 'closed') {this.audioCtx.close().then(() => {// 确保所有音频缓冲区已停止if (this.audioCtx.state === 'closed') {setTimeout(() => {// 重新创建 AudioContextthis.audioCtx = new (window.AudioContext || window.webkitAudioContext)();this.gainNode = this.audioCtx.createGain();this.gainNode.gain.value = 1;this.gainNode.connect(this.audioCtx.destination);this.startTime = this.audioCtx.currentTime;}, 100); // 延迟 100ms 后重新创建 AudioContext}});}
};export default PCMPlayer;

使用方法:

1 初始化:

var player = new PCMPlayer({encoding: '16bitInt',channels: 1,sampleRate: 16000,flushingTime: 1000
});

2 开始播放:

            // 处理音频数据const data = new Uint8Array('传入数据源');player.feed(data);

3 停止播放,清理暂存区

 player.stop()

这篇关于PCMPlayer播放器的使用教程(添加清理暂存区方法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136218

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔