Home > Blockchain >  Play sound from a font awesome icon
Play sound from a font awesome icon

Time:11-23

I am trying to play a sound when a font awesome icon is clicked.

I have a page where a list of posts are pulled from a database and I am using jinja to display them all. Each post will have an icon that can be clicked and the contents of that post will be read out.

This works if I just have an audio control but I would rather have a small icon instead of the entire audio control.

My issue is that when I add in the code to make it an icon, it only ever seems to run the 'src' of the first result in the for loop. I have inspected the page to check what each of the icons 'srcs' are and they are all different and correct but clicking the icon outputs the wrong audio.

I think it is something to do with the onclick event having an ID and the ID is always set to the first element in my forloop.

I tried this post - Play Sound when Font Awesome Icon is Clicked

HTML

{% extends "layout.html" %}
{% block content %}
    <!--Using Jinja2 to get run code in HTML-->
    <legend class="border-bottom mb-4">All Posts</legend>
    {% for post in posts %}
        <article class="media content-section">
            <div>
                <i class="fas fa-volume-up" onclick="playContent()" style="color: blue;"></i>
                <audio id="content">
                    <source src="link-to-blob-storage/{{ post.ttsFileName }}" type="audio/mp3">
                </audio>

                <script>
                    var audio = document.getElementById("content");

                    function playContent() {
                        audio.play();
                    }
                </script>               
            </div>
        </article>

    {% endfor %}

{% endblock content %}


CodePudding user response:

Try something like this:

{% for post in posts %}

    <audio id="audio_{{post.ttsFileName}}">
        <source src="{{post.ttsFileName}}" type="audio/mp3">
    </audio>
    <i onclick="document.getElementById('audio_{{post.ttsFileName}}').play()"></i>
    
{% endfor %}
        
  • Related