how to make a custom audioplayer play songs hosted online

Viewed 50

I want to use a custom audio player to play sound tracks hosted online.

For example I want to be able to feed the audio player a link like example.com/path/to/track.mp3 and it should parse it and play it. I can play sound tracks hosted locally

Here is the code where I have the problem. I have an audio object that points to a local folder where the sound tracks are. I am not sure how to deal with this when it is not hosted locally.

When I replace the path with the URL the audio player just freezes.

$(function () {
    var count = 0;
    var audio;

    //Hide Pause
    $('#pause').hide();

    initAudio($('#playlist li:first-child'));

    function initAudio(element) {
        var song = element.attr('song');
        var cover = element.attr('cover');
        var artist = element.attr('artist');
        var title = element.text();
        var temp = parseFloat($('#volume-slider').val() / 100);

        //Create audio object
        audio = new Audio('../media/books/' + song);

        audio.volume = temp;

        audio.addEventListener("loadedmetadata", function () {
            minutes = parseInt(audio.duration / 60);
            seconds = parseInt(audio.duration % 60);

            if (seconds < 10) {
                seconds = '0' + seconds;
            };
            if (minutes < 10) {
                minutes = '0' + minutes;
            };
        
            $('#duration').html(minutes + ':' + seconds);
        });

        $("#auto-play").click(function () {
            if (count === 1) {
                $("#auto-play").css("background-color", "black");
                count = 0;
            } else {
                $("#auto-play").css("background-color", "rgb(0,0,255)");
                count = 1;
            }
        });

        audio.addEventListener('ended', function () {
            if (count > 0) {
                var next = $('#playlist li.active').next();
                if (next.length == 0) {
                    next = $('#playlist li:first-child');
                }
                initAudio($(next));
                audio.play();
                showCurrentTime();
            }
        });

        //Inserts track info
        $('.artist').text(artist);
        $('.title').text(title);
        $('#duration').text();
        //Insert song cover. NOTE: the path below is relative to the 
        //html "img.cover" element not this js file.
        $('img.cover').attr('src', '../media/books/covers/' + cover);
        $('#playlist li').removeClass('active');
        element.addClass('active');
    };
});
1 Answers

You can avoid CORS errors with something like this. For your local development it would be easy. If you would like to go in production, it would be bit harder. The Server with the soundtracks has to accept your App.

Related