jQuery(document).ready(function($) {
// the audio loop trick is "alertCount" value, try playing around with it
var alarmData = {
"alertCount": 3,
"trigger": [{
"id": 47,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 48,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 49,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 50,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
}
]
};
var audioElements = document.getElementsByTagName('audio');
$.each(alarmData.trigger, function(index, alart_value) {
// update the status
// once the sounds are played (once for each alarm), then update the status for each alarm triggered
var countAlert = alarmData.alertCount;
if (alart_value.sound_triggered == null || alart_value.sound_triggered === false) {
audioElements[index].play(); // play the alert for first time
audioElements[index].onended = function() { // once finished, then play it according the number of alerts from backend(for jsfiddle purpose we use local data source)
if (index < --countAlert) {
this.play();
}
};
}
}); // close foreach loop for alertData.trigger
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<audio controls id="audio">
<source src="http://soundbible.com/grab.php?id=1599&type=mp3" type="audio/mpeg">
</audio>