I've encountered an issue with my HTML audio player in AngularJS. When the page is refreshed, everything works perfectly - I can set the source and play audio without any problems. However, if I navigate to another state in the app and then try to load/play the audio, multiple instances of the audio start playing simultaneously. This behavior repeats for each state change, leading to multiple instances of the audio playing at once.
Why is the audio player initializing repeatedly? How can I prevent this and keep it active as I switch between states without interrupting playback?
Here is a snippet of the relevant code. The view footer.html contains the directive and player, which are included by each state.
index.html :
...
<div style="clear:both"></div>
<div ui-view="footer"></div>
</body>
app.js :
.state('audiolist', {
url: '/audiolist/',
views: {
sideNav: {
templateUrl: 'views/sideNav.html',
controller: 'sideNavController'
},
header: {
templateUrl: 'views/header.html',
controller: 'headerController'
},
content: {
templateUrl: 'views/list.main.html',
controller: 'listController as content'
},
footer: {
templateUrl: 'views/footer.html',
controller: 'apController as ap'
}
})
...
.state('saveditems', {
url: '/saveditems/',
views: {
sideNav: {
templateUrl: 'views/sideNav.html',
controller: 'sideNavController'
},
header: {
templateUrl: 'views/header.html',
controller: 'headerController'
},
content: {
templateUrl: 'views/saveditems.main.html',
controller: 'savedItemsController as content'
},
footer: {
templateUrl: 'views/footer.html',
controller: 'apController as ap'
}
}
...
footer.html
<div class="audioplayer">
<!-- Audio Player -->
<hls-player id="player" playlist="{{ap.tracks}}"></hls-player>
...
directives/hlsPlayer.js
module.directive('hlsPlayer', function ($window, $templateRequest, $compile, $http, $rootScope) {
return {
restrict: 'AE',
link: function ($scope, element, attrs) {
$templateRequest("views/playerTemplate.html").then(function (html) {
// player functions
...
// play function
...
console.log("manifest loaded, found " + data.qualities + " quality level");
console.log("audio loaded and playing");
...
playerTemplate.html
...
<audio autobuffer preload="metadata" src="" id="radio" class="hidden" preload="none"></audio>
...