基于jmuxer的音频播放组件封装
创始人
2024-03-22 23:41:38
0

基于jmuxer的音频播放组件封装

参考Sonic平台

WebSocket封装

/*** WebSocket 封装* 主要功能:* 1. 自动重连;*/
export default class Socket {// WebSocket 实例ws// 相关配置项options// 错误消息队列errorStack = []// 是否正在重连isReconnectLoading = false// 定时器超时重连 IDtimeId = nullconstructor(options) {/*** options 支持传入参数* url websocket请求地址* node: 'player',* mode: 'audio',* debug: true,* flushingTime: 0,* reconnectDelay: 3000,* onopen,* onmessage,* onerror,* onclose*/this.options = {isErrorReconnect: true,...options}this.init()}/*** 初始化 WebSocket*/init() {if ('WebSocket' in window) {this.ws = new WebSocket(this.options.url);this.ws.binaryType = this.options.binaryTypethis.onOpen(this.options.onopen)this.onMessage(this.options.onmessage)this.onError(this.options.onerror)this.onClose(this.options.onclose)} else {console.error('该浏览器不支持WebSocket!');}}// 获取 WebSocket 实例get getWebSocket() {return this.ws}/*** 设置连接成功后的回调函数* @param {*} cb*/onOpen(cb) {this.ws.onopen = () => {console.log('websocket >>>> onOpen 连接成功!')// 发送成功连接之前所发送失败的消息this.errorStack.forEach(message => {this.send(message)})cb && cb()this.errorStack = []this.isReconnectLoading = false}}/*** 设置接收 WebSocket 消息的回调函数* @param {*} cb */onMessage(cb) {try {this.ws.onmessage = cb} catch (e) {console.error('error: ', e)}}/*** 设置连接失败后的回调函数* @param {*} cb */onError(cb) {this.ws.onerror = (err) => {console.error(err, 'websocket >>>> onError 连接异常!')cb && cb(err)if (!this.options.isErrorReconnect) returnthis.onReconnection()this.isReconnectLoading = false}}/*** 设置连接关闭后的回调函数* @param {*} cb */onClose(cb) {this.ws.onclose = () => {console.log('websocket >>>> onClose 关闭连接!')// 用户手动关闭的不重连if (this.isCustomClose) returncb && cb()this.onReconnection()this.isReconnectionLoading = false}}/*** 请求连接异常重连* @returns */onReconnection() {// 重连请求延时const delay = this.options.reconnectDelay || 3000// 防止重复请求if (this.isReconnectionLoading) {console.log('websocket >>>> onReconnection 请勿重复请求连接!')return}console.log('websocket >>>> onReconnection 正在重连!')this.isReconnectionLoading = trueclearTimeout(this.timeId)this.timeId = setTimeout(() => {this.init()}, delay)}/*** 手动发送请求* @param {*} message * @returns */handleSend(message) {// 连接失败时的处理if (this.ws.readyState !== WebSocket.OPEN) {console.error('websocket >>>> handleSend 请求发送失败!')this.errorStack.push(message)return}this.ws.send(message)}/*** 手动关闭连接*/handleClose() {this.isCustomClose = truethis.ws.close()}/*** 手动开启连接*/handleStart() {this.isCustomClose = falsethis.onReconnection()}/*** 手动销毁连接实例*/handleDestroy() {this.handleClose()this.ws = nullthis.errorStack = nullconsole.log('websocket >>>> handleDestroy 实例已销毁!')}
}

Audio-processor/index.js

音视频接受处理器

/**  Copyright (C) [SonicCloudOrg] Sonic Project**  Licensed under the Apache License, Version 2.0 (the "License");*  you may not use this file except in compliance with the License.*  You may obtain a copy of the License at**         http://www.apache.org/licenses/LICENSE-2.0**  Unless required by applicable law or agreed to in writing, software*  distributed under the License is distributed on an "AS IS" BASIS,*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*  See the License for the specific language governing permissions and*  limitations under the License.**/
/*** 音频接受处理器*/
import JMuxer from 'jmuxer';
import Socket from './socket';const DEFAULT_WS_URL = 'ws://localhost:8080';export default class AudioProcessor {constructor(options) {const wsUrl = options.wsUrl || DEFAULT_WS_URL/*** node: 'player',* mode: 'audio',* debug: true,* flushingTime: 0,* wsUrl*/this.jmuxer = new JMuxer({mode: 'audio',flushingTime: 0,// onReady() {// 	console.log('Jmuxer audio init onReady!');// },// onError(data) {// 	console.error('Buffer error encountered', data);// },...options});this.audioDom = document.getElementById(options.node)this.initWebSocket(wsUrl)}initWebSocket(url) {const that = thisthis.ws = new Socket({url,binaryType: 'arraybuffer',isErrorReconnect: false,onmessage: function(event) {var data = that.parse(event.data);data && that.jmuxer.feed(data);}});}/*** 音频解析* @param {*} data AAC Buffer 视频流* @returns */parse(data) {let input = new Uint8Array(data)return {audio: input};}onPlay() {this.audioDom.load()const playPromise = this.audioDom.play()if (playPromise !== undefined) {playPromise.then(() => {this.audioDom.play()})}}onPause() {this.audioDom.pause()}onReload() {this.audioDom.load()}onDestroy() {this.ws.handleClose()this.audioDom.pause()this.jmuxer.destroy()}
}

音频播放组件封装


相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
月入8000+的steam搬砖... 大家好,我是阿阳 今天要给大家介绍的是 steam 游戏搬砖项目,目前...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...