Home > Net >  Audio not playing on html page using flask
Audio not playing on html page using flask

Time:11-16

I am uploading and saving audio file to /static/uploads then trying to play it on my webpage however, uploaded audio(.wav) is not playing. Below is the flask code followed by HTML code.

server.py

@app.route('/audioupload', methods=['POST'])
def upload_files():
    file = request.files['file']
    filename = secure_filename(file.filename)
    if not file or file.filename == '':
        error = 'No selected file'
        return render_template(ERROR, error = error)     
    if file and allowed_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        # flash('file uploaded!')
        return render_template(UPLOAD)
@app.route('/audio_file_name')
def returnAudioFile(audio_file_name):
    path_to_audio_file = "app/static/uploads/" 
    return send_file(
        path_to_audio_file,
        mimetype="audio/wav",
        as_attachment=True
    )

upload.html

<form method="POST" enctype=multipart/form-data action="/audioupload">
    <input type=file name=file class="form-control-file" id="exampleFormControlFile1"><br>
    <input style="margin-right: 60px; background-color:#F7DE40; margin-top: 0px; margin-bottom: 0px;"  type=submit class="btn btn-light float-left" value="Upload!"><br><br>
    <audio controls><source src="http://127.0.0.1:5000/audio_file_name" type="audio/wav"></audio><br><br>
</form>

Please suggest.

html page, audio file upon uploading

CodePudding user response:

The rule for the route that enables the download does not contain a file name. This means that no parameters can be passed on to the route. See the documentation for variable rules.
The url is then created by url_for when the template is rendered.
I also recommend using the send_from_directory function.

import os
from glob import glob
from flask import Flask, flash, request, redirect, send_from_directory, url_for
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = {'wav'}

app = Flask(__name__)
app.secret_key = 'your secret here'
app.config['UPLOAD_FOLDER'] = os.path.join(app.static_folder, 'uploads')

def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    path = app.config['UPLOAD_FOLDER']
    files = [file[len(path) 1:] for file in glob(os.path.join(path, '*.wav'))]
    return render_template('index.html', files=files)

@app.route('/download/<path:filename>')
def download(filename):
    path = app.config['UPLOAD_FOLDER']
    return send_from_directory(
        path,
        filename,
        as_attachment=True,
        mimetype='audio/wav'
    )
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    {% with messages = get_flashed_messages() %}
      {% if messages %}
      <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
      {% endif %}
    {% endwith %}


    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" />
    </form>

    <ul>
      {% for filename in files %}
      <li>
        <audio controls>
          <source src="{{ url_for('download', filename=filename) }}" type="audio/wav">
        </audio>
      {% endfor %}
      </li>
    </ul>
  </body>
</html>

If you only want to offer the one audio file for listening that you have just uploaded, you have to slightly modify the example.
Remember the file can only be identified if it has just been uploaded. In order to access exactly this again later, the file name is required. For this reason, in the example above, I have listed all files that are in the folder.

@app.route('/', methods=['GET', 'POST'])
def index():
    filename = None
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return render_template('index.html', filename=filename)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    {% with messages = get_flashed_messages() %}
      {% if messages %}
      <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
      {% endif %}
    {% endwith %}


    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" />
    </form>

    {% if filename %}
        <audio controls>
          <source src="{{ url_for('download', filename=filename) }}" type="audio/wav">
        </audio>
    {% endif %}
  </body>
</html>

The rest of the code stays the same.

CodePudding user response:

I was able to solve this using below.

@app.route('/', methods=['GET', 'POST'])
def index():
    filename = None
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return render_template('index.html', filename=filename)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    {% with messages = get_flashed_messages() %}
      {% if messages %}
      <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
      </ul>
      {% endif %}
    {% endwith %}

    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" />
    </form>

    {% if filename %}
        <audio controls>
          <source src="{{ url_for('static', filename='uploads/'   filename) }}" type="audio/wav">
        </audio>
    {% endif %}
  </body>
</html>    
 
  • Related