Simple Audio Player

I wanted to post the solution I found so others could see. In the end it seems you have to use Javascript.

I created a custom HTML form called “Player” that has the HTML audio player and Javascript function. Here is the code:

<script>
  function loadClip(x){
    
    var player=document.getElementById('player');
    var sourceMp3=document.getElementById('player');
    sourceMp3.src=x;
  }
</script>

<figure>
    <audio controls preload="auto" controlsList="nodownload" id="player">
      <source id="sourceMp3" src="" type="audio/mp3" />
            Your browser does not support the
            <code>audio</code> element.
    </audio>
</figure>

Note how I put the script above the body (just like you would in Python). I then figured out how to call the Javascript function in Python on my form (although it could also be done in a server function). I chose to do it in the form as there is nothing sensitive about the function.

def button_click(self, **event_args):
  """This method is called when the button is clicked"""
  src_url = anvil.server.call('load_url')
  self.audio_player.call_js('loadClip', src_url)

I added the custom HTML form to my main form as an object called ‘audio_player’. I can then reference self.audio_player and use the call_js method. The src_url is loaded from a server function.

And it works! I’ve never used Javascript before but some helpful code snippets on StackOverflow and Jsfiddle got me there.

10 Likes