Open stream_url of a Soundcloud Track via Client-Side XHR?

 ̄綄美尐妖づ 提交于 2019-12-05 16:22:33

Well, as long as the Audio Files themselves don't come with the CORS headers (see curl -IL output in the question), the only solution that worked for me is open the audio files and add the headers yourself.

From my understanding, this is what other apps like https://github.com/tsenart/audiojedit do too. (in node.js) This has the the huge downside of shifting the traffic of the binary files to your server, which would be otherwise served by soundcloud.com.

You can use PHP to open the file, add the headers and restream it with something like:

$fp = fopen('http://api.soundcloud.com/tracks/[track_id]/stream.json?client_id=[client_id]', 'rb');

header("Content-Type: audio/mpeg");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE");
header("Access-Control-Allow-Headers: Accept, Authorization, Content-Type, Origin");
header("Access-Control-Allow-Origin: *");
fpassthru( $fp );

exit();

As I said, this is just a workaround, not a nice solution for a production environment, but helped me keep going with my Web Audio App.

Soundcloud, any chance of adding CORS headers to the audiofiles? :)

If you're not necessarily tied down to using XHR, you could create new <audio/> elements and set their src to whatever asset you want, without being tied to Same-Origin Policy.

Newer versions of Chrome will allow you to create AudioNode instances from media elements via MediaElementAudioSourceNode -- so you can still use all the cool new Web Audio stuff.

var audio, body, context, source;
audio = document.createElement('audio');
body = document.getElementsByTagName('body')[0];
audio.setAttribute('src', 'http://kevincennis.com/mix/assets/sounds/1901_gtr1.mp3');
body.appendChild(audio);
context = new webkitAudioContext();
source = context.createMediaElementSource(audio);
source.connect(context.destination);
source.mediaElement.play();

Excuse the hideous code. It's late and I'm tired.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!