js-php-audioAPI利用AJAX处理后端传来的mp3流文件数据

2024-09-05 11:48

本文主要是介绍js-php-audioAPI利用AJAX处理后端传来的mp3流文件数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

js-php-audioAPI利用AJAX处理后端传来的mp3流文件数据 目录

文章目录

  • 前言
  • 推荐阅读
  • 常见`API`
  • 代码实现
    • `audio.html`
    • `streamFile.php`
  • 总结


前言

  • 尝试利用浏览器中的audio API

推荐阅读

  • MDN

常见API

  • AudioContext
  • decodeAudioData

代码实现

audio.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>audio api</title>
</head>
<body>
<!--<audio controls="controls" autoplay="autoplay">-->
<!--    <source src="test.mp3" type="audio/mpeg">-->
<!--</audio>--><!--<input id="file" type="file">-->
</body>
<script>
init();
// getFile();
function init() {// AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;let aCtx;try{aCtx = new (window.AudioContext || window.webkitAudioContext)();}catch (e) {console.log(e);}play(aCtx, 'http://localhost:83/streamFile.php');}//    file
function getFile() {const fileDom = document.getElementById('file');fileDom.addEventListener('change', event=>{const file = event.target.files[0];console.log(file);const fileReader = new FileReader();const audioContext = new (window.AudioContext || window.webkitAudioContext)();fileReader.readAsArrayBuffer(file);fileReader.onload = ()=>{console.log(audioContext);audioContext.decodeAudioData(fileReader.result, result=>{console.log('start');console.log(result);const source = audioContext.createBufferSource();source.buffer = result;source.connect(audioContext.destination);source.start();},err =>{console.log(`decodeAudioData error:${err}`);});};});
}//    加载音乐function load(ctx, fUrl, succFN, failFN) {let req = new XMLHttpRequest();req.open('GET', fUrl, true);req.responseType = 'arraybuffer';req.onprogress = data => {console.log(`data:${data}`);console.log(`response:${req.response.byteLength}`);};//旧版的回调函数//异步解码req.onload = function () {console.log(this.response);//    解码ctx.decodeAudioData(this.response,buf =>{succFN && succFN(buf);},(err) => {failFN && failFN(err);});}//新版的promise// req.onload = function () {//     ctx.decodeAudioData(this.response)//         .then();// }req.send();}//播放音频function play(ctx, fUrl) {load(ctx, fUrl, buf => {//测试是否进入console.log('Enter decode...');//创建一个node对象let sNode = ctx.createBufferSource();// console.log(buf);sNode.buffer = buf;//连接到destination节点进行播放sNode.connect(ctx.destination);sNode.start(0);sNode.loop = true;}, err => {console.log(`Error with decoding ${err}`);});}
</script>
</html>

streamFile.php

<?phpnamespace streamFile;
spl_autoload_register(function (string $className){require_once $className . ".php";
});class streamFile
{private $file;/** @param String $file 要发送的文件* */public function __construct(string $file){$this->file = $file;}public function sendStreamFile() {if (!file_exists($this->file))   return false;$opt = array('http' => array('method' => 'POST','header' => 'Content-Type: audio/mpeg'));//        header('content-Transfer-Encoding: binary');
//        header('Progma: no-cache');
//        header('icy-br: 128');$context = stream_context_create($opt);$response = file_get_contents($this->file, false, $context);return $response;}public function openFile(){$fp = fopen($this->file, "r");header("Content-type: application/octet-stream");header("Accept-Ranges: bytes");header("Content-Disposition: attachment; filename=test.mp3");$buffer = 1024;while (!feof($fp)){$file_con = fread($fp, $buffer);echo $file_con;}fclose($fp);}
}$ret = new streamFile('test.mp3');
var_dump($ret->openFile());//echo 'start';

总结

  • 如果出现Uncaught (in promise) DOMException: Unable to decode audio data这种报错,毫无疑问,是后端传来的二进制数据存在问题,需要后端进行修改。

这篇关于js-php-audioAPI利用AJAX处理后端传来的mp3流文件数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

pandas数据的合并concat()和merge()方式

《pandas数据的合并concat()和merge()方式》Pandas中concat沿轴合并数据框(行或列),merge基于键连接(内/外/左/右),concat用于纵向或横向拼接,merge用于... 目录concat() 轴向连接合并(1) join='outer',axis=0(2)join='o

批量导入txt数据到的redis过程

《批量导入txt数据到的redis过程》用户通过将Redis命令逐行写入txt文件,利用管道模式运行客户端,成功执行批量删除以Product*匹配的Key操作,提高了数据清理效率... 目录批量导入txt数据到Redisjs把redis命令按一条 一行写到txt中管道命令运行redis客户端成功了批量删除k

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使