简体   繁体   English

播放HTML5中的JavaScript音频而没有文件-使用缓冲区

[英]Play audio from javascript in HTML5 WITHOUT a file - using buffer

I'm using jQuery's ajax method to call a PHP script on the server which will return an mp3 file to me, so I have the data in a variable to the success function. 我正在使用jQuery的ajax方法在服务器上调用PHP脚本,该脚本将向我返回mp3文件,因此我将数据包含在成功函数的变量中。 Now I want to play that audio for the person. 现在,我想为那个人播放音频。 I am using HTML5, but every example I've seen expects you to point at a file that has the audio. 我正在使用HTML5,但是我所看到的每个示例都希望您指向一个带有音频的文件。 I don't have it as a file, I have it in memory. 我没有它作为文件,我已经在内存中。

Here is something to get you started using the Web Audio API. 这是使您开始使用Web Audio API的方法。 theAjaxResponse should be the mp3 response, in binary, from the server. theAjaxResponse应该是来自服务器的mp3响应(以二进制形式)。

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();

context.decodeAudioData(theAjaxResponse, function(buffer) {
      var source = context.createBufferSource();
      source.buffer = buffer;
      source.connect(context.destination);
      source.start(0);
}, onError);

This will only work in modern browsers supporting the Web Audio API. 这仅在支持Web Audio API的现代浏览器中有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM