Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mediaelement.js occasionally playing cached instead of live mp3 stream #1321

Closed
nicolasschabram opened this issue Oct 4, 2014 · 12 comments
Closed

Comments

@nicolasschabram
Copy link

Hey guys,

I built a player which is successfully streaming mp3 (IceCast). However every once in a while it suddenly plays cached content from minutes ago instead of the actual live stream. There's a play/pause button. Muting instead of pausing made it a little bit better but there are still hiccups. Is there anything I can do to solve this problem?

This is my current html setup:

<audio id="webradio" src="http://XX.XXX.XXX.XX:8000/stream.mp3" type="audio/mp3"></audio>

... and jQuery:

var webradio = $('#webradio');
if (webradio.length){
    MediaElement('webradio', {success: function(me) {
        // volume slider
        var slider = $('#volume');
        slider.slider({
            value:      80,
            change:     function( event, ui ) {},
            range:      'min'
        });
        var newVolume;
        slider.on('slidechange', function( event, ui ) {
            newVolume = slider.slider( "option", "value" ) / 100;
            me.setVolume(newVolume);
        } );

        me.play();
        me.setVolume(0.8);
        var vol;
        document.getElementById('play-pause')['onclick'] = function() {
            if (me.volume == 0) {
                me.setVolume(vol);
                $('#play-pause').removeClass('paused');
            } else {
                vol = me.volume;
                me.setVolume(0);
                $('#play-pause').addClass('paused');
            }
        };
    }});
}

Thanks a lot!
Nicolas

@nicolasschabram nicolasschabram changed the title Mediaelement.js occasionally playing cached instead of live mp3 stream mediaelement.js occasionally playing cached instead of live mp3 stream Oct 4, 2014
@adsonnunes
Copy link

I've got the same problem. Can anyone help me? I'd like to stop the audio instead pause it.

@moo-farag
Copy link

I had the same problem, Fixed by:

  • on pause: set source to "" (add event listener)
  • adding a play func that sets the source to http:// xxxx?nocache=RANDOMNUMBER

Here is my code block:

  $jq(document).ready(function () {
      $jq("#playBtn").hide();
      window.addEventListener("keydown", function(e) {
            // space and arrow keys
            if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
                e.preventDefault();
            }
        }, false);
      $jq("#slider").slider({
            value : $jq('audio')[0].player.media.volume*100,
            step  : 1,
            range : 'min',
            min   : 0,
            max   : 100,
            slide : function(){
                var value = $jq("#slider").slider("value");
                $jq('audio')[0].player.media.volume = (value / 100);
            }
        });
  });  

  $jq("#slider").on( "slidechange", function( event, ui ) {
        var value = $jq("#slider").slider("value");
        $jq('audio')[0].player.media.volume = (value / 100);
  } );

  var player = new MediaElementPlayer('.audioPlayer', {
      audioWidth: 0,
      audioHeight: 0,
      loop: false,
      enableAutosize: false,
      enableKeyboard: false,
      features: ['playpause', 'volume'],
      showPosterWhenEnded: false,
      pauseOtherPlayers: true,
        success: function (mediaElement, domObject) {
            mediaElement.addEventListener('pause', function () {
                mediaElement.setSrc('');
            }, false);
        },
        error: function (mediaElement, domObject) {
            alert('Stopped !!');
        }
    });

var currentVolume = Math.round($jq('audio')[0].player.media.volume * 100) / 100;

function playPlayer() {
     var nocache = Math.floor((Math.random() * 1000000) + 1);
     player.setSrc('${streamingURL}?nocache='+nocache);
     player.play();
     $jq("#pauseBtn").show();
     $jq("#playBtn").hide();
}

function pausePlayer() {
    player.pause();
    player.setSrc('');
    $jq("#playBtn").show();
    $jq("#pauseBtn").hide();
  }

function fullVol() {
    $jq('audio')[0].player.media.volume = 1;
    $jq("#slider").slider("value", 100);
}

function mute() {
    $jq('audio')[0].player.media.volume = 0;
    $jq("#slider").slider("value", 0);
}

@nicolasschabram
Copy link
Author

Damn, you're a genius, @moo-farag! This worked perfectly for me!

Here are the essential parts of my version:

MediaElement('webradio', {success: function(me) {
    // Generate random number and append to the streaming URL's get parameters
    // in order to avoid cached playback.
    var source = webradio.attr('src');
    var i = Math.floor( ( Math.random() * 1000000 ) + 1 );
    me.setSrc( source + '?nocache=' + i );

    // Start player.
    me.play();


    // Some mobile devices don't allow autoplay
    // Check if player is paused after me.play(); above.
    // If yes, remove src from player.
    var playPause = $('#play-pause');
    if ( me.paused == true ) {
        me.setSrc('');
    }


    // Play and pause player on click.
    // Increase nocache number in src url every time to avoid cached playback.
    document.getElementById('play-pause')['onclick'] = function() {
        if (me.paused) {
            i++;
            me.setSrc(source + '?nocache=' + i);
            me.play();
        } else {
            me.setSrc('');
        }
    };
}});

Thank you!

@moo-farag
Copy link

@nicolasschabram ,, I added some event listeners for "error" and "stall" events that reconnects automatically according to "netStat" (dc from streaming service or from the user, usefull for bad connections).

on page load Initialize:

function initPlayer() {
player = new MediaElementPlayer('.audioPlayer', {
audioWidth: 0,
audioHeight: 0,
loop: false,
enableAutosize: false,
enableKeyboard: false,
features: ['playpause', 'volume'],
poster: '${currentLiveProgram.imageFile.downloadURL}',
showPosterWhenEnded: false,
pauseOtherPlayers: true,
success: function (mediaElement, domObject) {
mediaElement.addEventListener('pause', function () {
mediaElement.setSrc('');
}, false);

        mediaElement.addEventListener('stalled', function () {
                var checkNetworkStateTimer = setInterval(function () {
                    if (!paused) {
                        if (domObject.networkState == 1 || domObject.networkState == 3) {
                            var nocache = Math.floor((Math.random() * 1000000) + 1);
                            mediaElement.setSrc('${streamingURL}?nocache='+nocache);
                            mediaElement.load();
                            mediaElement.play();
                            console.log('re-connecting after stalling due to networkState: '+domObject.networkState); //2 indicates NETWORK_LOADING state
                        }
                    }
                }, 3000);

            }, false);
    mediaElement.addEventListener('error', function () {
        var checkNetworkStateTimer = setInterval(function () {
            if (!paused) {
                if (domObject.networkState == 1 || domObject.networkState == 3) {
                    var nocache = Math.floor((Math.random() * 1000000) + 1);
                    mediaElement.setSrc('${streamingURL}?nocache='+nocache);
                    mediaElement.load();
                    mediaElement.play();
                    console.log('re-connecting after error due to networkState: '+domObject.networkState); //2 indicates NETWORK_LOADING state
                }
            }
        }, 3000);
      }, false);




        },
        error: function () {
            console.log('error log');
        }
    });

Global Vars:
var player;
var paused = false;

"paused" is used to keed track wether the player is paused or not (as $jq('audio')[0].player.media.paused returned wrong values)

I'm facing some problems with mobile version, will attach it once finished

@nicolasschabram
Copy link
Author

Hey @moo-farag, it's been a while. Now I finally found the time to look into this again. I indeed do have some issues with the player stopping because of network errors. I haven't tried your solution yet (thanks for sharing though!). I first wanted to ask if you already resolved the problems with the mobile version you talked about.

@NitroxydeX
Copy link

Hey Guys,

searching for the same thing like you. Can someone help me? I doesen't get your codes.. atm I load the Player with:

<script type="text/javascript">
$(function(){
  $('#audio-player').mediaelementplayer({
    alwaysShowControls: true,
    features: ['playpause','volume'],
    audioVolume: 'horizontal',
    audioWidth: 450,
    audioHeight: 70,
    iPadUseNativeControls: true,
    iPhoneUseNativeControls: true,
    AndroidUseNativeControls: true
  });
});
</script>

What I have to add to tell him that Pause is Stop?

@NitroxydeX
Copy link

Okay. mastered it.. This is my Script:

<script>
  window.onload = function() {
  myaudio = document.getElementById('audio-player');
  button = $('.mejs-playpause-button');
  i = Math.floor( ( Math.random() * 1000000 ) + 1);
  source = 'http://localhost:8000/;';
  playpause = document.querySelector('.mejs-playpause-button');
  playpause.addEventListener('click', function() {
    if (myaudio.paused) {
        myaudio.setSrc('');
        myaudio.load();
        myaudio.pause();
        button.removeClass('mejs-pause').addClass('mejs-play');
    } else {
        i++;
        myaudio.setSrc(source + '?nocache=' + i);
        myaudio.load();
        myaudio.play();
        button.removeClass('mejs-play').addClass('mejs-pause');
    }
  });
 };
</script>

@rafa8626
Copy link
Contributor

@nicolasschabram Closing old issues. If you'd like to reopen this, let us know. Thanks!

@sistematico
Copy link

The parameter forceLive replace this code?

@rafa8626
Copy link
Contributor

No it doesn’t

@rafa8626
Copy link
Contributor

ForceLive is mostly to avoid displaying the controls’ progress bar on a live source

@sistematico
Copy link

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants