Question

I have rails application with host http://myhost.dev, and it searching music using API of vk.com (russian facebook), so, it provides search method audio.search . This is my search.js.erb which called with remote link to search action of some controller:

VK.api('audio.search',{q: "<%= j params[:query] %>", auto_complete: "1", sort: "2", count: "200"},function(data){
  if(data.response) {
    $(function() {
      var audio = $('audio');
      // Setup the audio.js player
      var a = audiojs.create(audio);
      });
      // Load in the first track
      var audio = a[0];
          first = $('ol a').attr('data-src');

      console.log(first);
      $(".song-title").text($('ol a').first().text());
      $('ol li').first().addClass('playing');

      // load resource to player
      audio.load(first);
      });
    });

  }

  else {
    /* handle error */
  }
});

My application.js:

  // initiate vk application
  VK.init({
    apiId: '3650724'
  });

It's all okay, it's all working, but, it doesn't on the other route! For example, on the route http://myhost.dev/foo I have another one audio tag, and code like this:

:javascript
  var artist = '#{ @artist.name }';
  // Setup the player to autoplay the next track

  // Setup the player to autoplay the next track

  // Load in the first track
  var track_name = $('ol a').first().attr('data-src');
  VK.api('audio.search',{q: artist + " - " + track_name, auto_complete: "1", sort: "0", count: "1"},function(data){
    if(data.response) {
      $(function() { 
        alert("lol");
        var audio = $('audio');
        var a = audiojs.create(audio);
        var first_track = data.response[1];
        $(".song-title").text(first_track.title);
        $('ol li').first().addClass('playing');

        console.log(first_track.url);
        audio.load(first_track.url);
      });
    }
    else {
      alert("fail!");
    }
  });

It returns valid json response, but when loading resource url to player it gives me

XMLHttpRequest cannot load http://cs4967.vk.me/u5366455/audios/some.mp3. Origin http://myhost.dev is not allowed by Access-Control-Allow-Origin.
Was it helpful?

Solution

This is not a problem with your API requests, but with the <audio /> element (and <video /> for that matter) only requests to be made on the same domain.

VK does not emit CORS headers for the URL you listed (albeit it is a 404). If this is the case, you might have to use your own server as a proxy, and retrieve the mp3s onto your server, and stream them from there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top