Home > Back-end >  Reading audio/mp3 file from GCP bucket throws blocked by CORS policy: No 'Access-Control-Allow-
Reading audio/mp3 file from GCP bucket throws blocked by CORS policy: No 'Access-Control-Allow-

Time:01-25

I'm trying to create a audio player using js and flask. The audio files are retreived from a GCP bucket and audio files have Public Access. But when I try to play the audio it throws,

Access to audio at 'https://storage.googleapis.com/blah-bucket-1/audio-files/13_chapter_.mp3' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://storage.googleapis.com/blah-bucket-1/audio-files/13_chapter_.mp3 net::ERR_FAILED 206

My HTML code looks like this:

<audio  src="https://storage.googleapis.com/blah-bucket-1/audio-files/13_chapter_.mp3" crossorigin="anonymous">
  <source src="https://storage.googleapis.com/blah-bucket-1/audio-files/13_chapter_.mp3" type="audio/mp3">
</audio>
<ul id="audio-playlist" >
  <li style="cursor:pointer;" title="Chapter 01" data-chapter-id="1" index="1" path="https://storage.googleapis.com/blah-bucket-1/audio-files/13_chapter_.mp3">
    ▶ Chapter 01
  </li>
</ul>
<input type="range" id="seek-bar" value="0" style="display: block;width: 500px;">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV 4mjoKBsE4x3H BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
  var playlist = document.querySelector("#audio-playlist");
  var total_songs = playlist.children.length;
  
  var default_volume = 0.05;
  $(".volume-count").html((default_volume*300)/3);
  
  var seek_bar = document.querySelector("#seek-bar");
  seek_bar.value = 0;
  
  var audio_source = document.querySelector(".js-audio-source");
  var current_song = 0;


  var audio_api;
  var gain_node;
  var analyser_node;
  var track;
  var interval;

  function init(){
    audio_source.src = playlist.children[current_song].getAttribute("path");
    var playingChapterID = playlist.children[current_song].getAttribute("data-chapter-id");
    audio_source.volume = default_volume;
    audio_source.crossOrigin = "anonymous";
  }
  init()
  
  playlist.addEventListener('click', function(e){
    current_song = parseInt(e.target.getAttribute("index"))-1 ;
    init();
    play();
  });
  
  function song(path){
    audio_source.src = path;
  }
  
  function play(){
    audio_source.play();
    interval = setInterval(update_seek, 60);
    if(audio_api === undefined){
      audio_api = new window.AudioContext() || new window.WebkitAudioContext();
      gain_node = audio_api.createGain();
      analyser_node = audio_api.createAnalyser();
      track = audio_api.createMediaElementSource(audio_source);
    }
    track.connect(analyser_node).connect(gain_node).connect(audio_api.destination);
  }
  function pause(){
    audio_source.pause();
    clearInterval(interval);
  }
  function update_seek(){
    seek_bar.value = (audio_source.currentTime/audio_source.duration)*100;
  }
  $(document).keydown(function(e) {
    if (e.keyCode == 32) {  // Space key
      e.preventDefault();
      play()
    }
    if (e.keyCode == 27) {  // Space key
      e.preventDefault();
      pause()
    }
  });
</script>

I tried adding audio_source.crossOrigin = "anonymous"; to the init() function and also tried adding crossorigin="anonymous" prop to the audio tag too. But it doesn't seem to work.

Player works fine(at least play, pause and seek update) with local audio files. And when I open GCP bucket audio URL in browser directly, it plays without an issue.

How can I fix this? Pls help.

CodePudding user response:

Try configure CORS on the GCP bucket that contains the audio files.You can check this document1 & document2 on how to configure CORS for GCP bucket

gsutil cors set cors-json-file gs://<bucket_name>

That will upload those CORS config settings to your bucket. And after that you can retrieve the current settings at any time using gsutil cors get gs://<bucket_name>.

gsutil cors allows you to get or set the CORS configuration on one or more buckets. This is supported for buckets only, not objects. An example CORS JSON document looks like the following:

[
    {
      "origin": ["http://localhost”],
      "method": ["GET"],
      "responseHeader": ["Content-Type"],
      "maxAgeSeconds": 3600
    }
]

Also check the below similar examples

CORS set but not affecting the request

gs:// has no CORS configuration

Why is Google Cloud Storage always answering with cors error: No 'Access-Control-Allow-Origin' header is present on the requested resource

  • Related