Reputation: 1221
I'm new in Django and JS. Trying to create HTML5 audioplayer with custom controls. When I start page nothing happens.
Tested this mp3 with default player and everything is ok. So I think static settings is correct.
..stream (the app)
....static
......stream
........audio
..........test.mp3
........scripts
..........player.js
....templates
......index.html
This is my index.html. The base template is almost empty.
{% extends "base_generic.html" %}
{% block content %}
{% load static %}
<script src="{% static "stream/scripts/player.js" %}" type="text/javascript"></script>
<audio src="{% static "stream/audio/test.mp3" %}" type="audio/mpeg">
{% endblock %}
And this is my player.js
var aud = $('audio')[0];
aud.play();
I expect that when I open the page, the music would start playing.
Upvotes: 1
Views: 262
Reputation: 13327
The issue comes from the JS script execution. At the time the browser executes
var aud = $('audio')[0];
aud.play();
or
document.getElementsByTagName('audio')[0].play();
the audio block is not created yet, so the query cannot find anything and you get the error
Uncaught TypeError: Cannot read property 'play' of undefined
You can delay the execution with the following function :
document.addEventListener('DOMContentLoaded', function(){
var aud = document.getElementsByTagName('audio')[0];
aud.play();
}, false);
Upvotes: 1