php 跨域读取mp3
时间: 2023-07-12 21:03:34 浏览: 63
跨域读取mp3文件的方法与读取其他类型文件的方法类似,可以通过设置服务器响应头来解决跨域问题。具体步骤如下:
1. 在服务器端设置响应头Access-Control-Allow-Origin来允许跨域访问,例如:
```
header('Access-Control-Allow-Origin: *');
```
2. 在客户端使用XMLHttpRequest对象读取mp3文件,并设置responseType为"arraybuffer",例如:
```
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/test.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
var audioContext = new AudioContext();
audioContext.decodeAudioData(xhr.response, function (buffer) {
var source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start();
});
};
xhr.send();
```
以上代码可以读取mp3文件,并将其解析成音频缓冲区,最后播放出来。请注意,由于mp3文件是二进制文件,因此需要设置responseType为"arraybuffer",否则无法正确读取。