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 pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali