Thom Ernst
Thom Ernst

Reputation: 409

Play html5 sound files with flask

I would like to use a class Track to have a function playsound() and this should play the sound on a html template.

This is my class :

class Track:
def __init__(self, name, path):
    self.name = name
    self.path = path

def playsound(self):
    # does something

Now I know that I will need javascript and ajax as well probably. But I'm still new to the concept and I would like to see how I would go about achieving that. The sound file should play onload and should simply be invoked when you type:

songname = Track('name', 'music/filename.ogg')

@app.route('/playSong')
def playSong():
    return songname.play()

If there is no way this can be done in this way, or there is a much better way, I'd be happy to be enlightened. Thanks in advance!

Upvotes: 0

Views: 4809

Answers (2)

Cristeena Joseph
Cristeena Joseph

Reputation: 21

You can keep the src of in HTML as

  <audio controls>
   <source src="http://127.0.0.1:5000/a" type="audio/wav"/>
  </audio>

where http://127.0.0.1:5000/a is the url which send_file the audio

python code :

@app.route('/a')
def returnAudioFile():
    path_to_audio_file = pwd+"\\question_folder\\audio.wav" #audio from project dir
    return send_file(
       path_to_audio_file, 
       mimetype="audio/wav", 
       as_attachment=True, 
       attachment_filename="test.wav")

Upvotes: 1

Muhamed Paric
Muhamed Paric

Reputation: 20

If I understood the question correctly, you should put an <audio> HTML element in your template and go from there. Flask will only serve the rendered template, it can't play the sound directly.

Upvotes: 0

Related Questions