Fadly Dzil
Fadly Dzil

Reputation: 2206

playing audio in ajax callback

I create some jquery's code to auto refresh the specific div. In auto refresh I using ajax to create some notification if there have a new request from my client, like a social network notif. I use a music for the notif. When a new request comes, the music is on. Before music is finished, the next notif comes, and the music on too. So, there are two music are playing and this looked like a bug.

I want just to play one music, even the next or so on come. What should I do? Should I check in success ajax if music is played?

function refresh() {
    var ini;
    var requestMasuk = $('#request_belum_terima').text();
    var audioElement = document.createElement('audio');

    audioElement.setAttribute('src', '<?php echo base_url() . 'assets/music/noty.mp3'; ?>');


    audioElement.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    var myAudio = document.getElementsByTagName('audio');

    setTimeout(function() {
        $.ajax({
            url: '<?php echo base_url() . 'control_closing/hitungRequestBelumTerima/' ?>',
            type: 'POST',
            dataType: 'json',
            success: function(obj) {
                if (obj > requestMasuk) {
                    ini = obj;
                    $('#request_belum_terima').text(obj);
                    ==========   Failed  ==========================
                    if (myAudio.duration > 0 && !myAudio.paused) {

                        alert('Another Request is come');

                    } else {
                        audioElement.play();
                    }
                   =================================================
                    alert("New Request is come");
                    $('#things_table').fadeOut('slow').load('<?php echo base_url() . 'monitoring/ajax_get_things_table' ?>').fadeIn('slow');
                }
                refresh();


            }
        }).always(function() {
            $('#request_belum_terima').text(ini);
        }).done(function() {
            $('#request_belum_terima').text(ini);
        });
    }, 20000);
    $('#request_belum_terima').text(ini);
}

Upvotes: 1

Views: 1227

Answers (1)

hazelnut
hazelnut

Reputation: 157

The variable myAudio returns an array. Later on you check for !myAudio.paused which can't work as it expects a single audio element - not an array.

If it's all the time the same mp3 I would recommend to use a single audio element and not create every time a new one. Check that element and play if it's paused.

Upvotes: 1

Related Questions