0

I am making a custom audio player with javascript. In this I need to knoe the amount of data buffered. For this I am using the following code:

$("#active-song")[0].addEventListener('loadedmetadata', function() {    

    $("#active-song")[0].addEventListener('progress', function() {
        songs.duration = $("#active-song")[0].duration ;
        var buff786 =  $("#active-song")[0].buffered.end(0);    
        var percent-buffered = (buff786/songs.duration) * 100;          
        $(".song-progress .current-progress").css("width", percent-buffered + "%");
    });
});

The problem is that before anything could happen I get an error in the console. The error exists because when the javascript code is parsed by the browser the song hasn't yet been buffered. So the var buf786 remain undefined and I get the error: Uncaught SyntaxError: Unexpected token. I tried many aliters such as:

var buff786 =  $("#active-song")[0].buffered.end(0);
if (buff786 == undefined) {
  buff786 = 1;
}
var percent-buffered = (buff786/songs.duration) * 100;   

Still I get the error. So how do I bypass this error. Can I parse expressions like non-existing-random + 100 in javascript?

user31782
  • 7,087
  • 14
  • 68
  • 143
  • can you show the full error stacktrace? it might help :) – Arnelle Balane Jun 19 '16 at 13:27
  • 3
    The error you're getting is from `var percent-buffered`. You can't use `-` as part of a variable name. – Pointy Jun 19 '16 at 13:27
  • have you tried to `setTimeout` before you read the variable? – warkentien2 Jun 19 '16 at 13:27
  • @Pointy It seems `percent-buffered` is actually the issue. AFter changing its name things are working fine. – user31782 Jun 19 '16 at 13:32
  • `Uncaught Syntaxerror` does **not** mean that a variable is undefined. It means there's a syntax error. –  Jun 19 '16 at 14:07
  • See http://stackoverflow.com/questions/1661197/what-characters-are-valid-for-javascript-variable-names. –  Jun 19 '16 at 14:09
  • Additional, just FYI: The code assumes there will only be one buffered segment which is not necessary the case. You have to sum up all potential buffer ranges to get the correct result. –  Jun 19 '16 at 21:49
  • @K3N So I should use `$("#active-song")[0].buffered.end($("active-song")[0].buffered.length - 1)?` – user31782 Jun 20 '16 at 05:11
  • @user31782 here's an example of iterating through buffer ranges, it's for video but would be the same for audio: http://stackoverflow.com/questions/18422517/html5-video-buffered-attribute-features/18624833#18624833 –  Jun 20 '16 at 05:18

0 Answers0