我只是尝试播放一个pcm音频女巫浏览器,所以我找了一些带有WEB音频的API,我就找到了它:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext.decodeAudioData。然后我用它写一个例子。 java脚本文件代码是:
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
}
);
}
request.onerror = function() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
window.onload = init;
var context;
var bufferLoader;
function init() {
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
} catch(e) {
alert('Web Audio API is not supported in this browser');
}
bufferLoader = new BufferLoader(
context,
[
'http://localhost:91/learn/audio'
],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList) {
var source = context.createBufferSource();
source.buffer = bufferList[0];
source.loop = true;
source.connect(context.destination);
source.start(0);
}
这是服务器核心宽度servlet下载:
@WebServlet(name = "audioServlet", urlPatterns = "/audio")
public class AudioServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletOutputStream stream = null;
BufferedInputStream buf = null;
File pcmFile = new File("D:/2033.pcm");
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Content-Disposition", "filename=2033.pcm");
resp.setContentType("audio/basic");
resp.setContentLength((int) pcmFile.length());
FileInputStream input = new FileInputStream(pcmFile);
try {
buf = new BufferedInputStream(input);
stream = resp.getOutputStream();
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}
} catch (IOException ioe) {
throw new ServletException(ioe.toString());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
}
但是当我在Chrome中浏览这个html文件时,它会播放任何声音,并且当它运行时没有任何错误。我也尝试了mp3或ogg音频文件,它可以效果最好。为什么?谁能帮我解决。您可以在http://pan.baidu.com/s/1XAhC
下载pcm音频文件