在javascript mp3中的CORS请求

时间:2018-01-20 22:45:49

标签: javascript cors

我一直在尝试使用来自我的远程服务器的源.mp3文件创建音频元素。但我得到了这个错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

经过一番研究后,我配置了我的远程服务器的.htaccess文件,以便接受cors请求。

但是我无法弄清楚如何告诉javascript获取远程mp3文件并将其作为我的音频元素的源。我怎样才能实现它?

.htaccess文件:

Handling Options for the CORS
 RewriteCond %{REQUEST_METHOD} OPTIONS
 RewriteRule ^(.*)$ $1 [L,R=204]

Header set X-Content-Type-Options "nosniff"
Header set X-XSS-Protection "1; mode=block"
   # Always set these headers for CORS.
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$
Header always set Access-Control-Allow-Credentials true

我试过的html文件:



<a href="#" onclick="makeCorsRequest(); return false;">Run Sample</a>
<audio id="audio" controls="controls"></audio>
<script type="text/javascript">

  // Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {

  // This is a sample server that supports CORS.
  var url = 'www.ttt.com/urlof_MP3.mp3';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();

  var audio = document.getElementById("audio");
  audio.src = xhr.responseText;

}
</script>
&#13;
&#13;
&#13;

0 个答案:

没有答案