How to reconnect to a stream automatically¶
Step by step code sample¶
If WebRTC stream playback is stopped by some reason, an automatic reconnection can be implemented by tweaking Player example code as follows:
-
Add the variables to configure autonmatic reconnection to the script beginning
In this example, player will try to reconnect to the stream every 3 seconds until 100 tries are expired. Therefore, maximum time to wait for the stream to be restored is 5 minutes, then automatic reconnection is cancelled -
Add clearRestart() function call to clear reconnection timer if enabled to
STREAM_STATUS.PLAYING
handler -
Add tryToRestart() function call to enable reconnection timer to
SESSION_STATUS.FAILED
handlerfunction start() { var url = $('#url').val(); ... Flashphoner.createSession({urlServer: url}).on(SESSION_STATUS.ESTABLISHED, function(session){ ... }).on(SESSION_STATUS.DISCONNECTED, function(){ ... }).on(SESSION_STATUS.FAILED, function(){ setStatus(SESSION_STATUS.FAILED); onStopped(); tryToRestart(); }); }
-
Add
clearRestart()
function call to clear reconnection timer if enabled toSTREAM_STATUS.STOPPED
handlerfunction playStream(session) { ... stream = session.createStream(options).on(STREAM_STATUS.PENDING, function (stream) { ... }).on(STREAM_STATUS.PLAYING, function (stream) { ... }).on(STREAM_STATUS.STOPPED, function () { $("#preloader").hide(); setStatus(STREAM_STATUS.STOPPED); clearRestart(); onStopped(); }).on(STREAM_STATUS.FAILED, function(stream) { ... }).on(STREAM_STATUS.NOT_ENOUGH_BANDWIDTH, function(stream){ ... }); stream.play(); }
-
Add
tryToRestart()
function call to enable reconnection timer toSTREAM_STATUS.FAILED
handlerfunction playStream(session) { ... stream = session.createStream(options).on(STREAM_STATUS.PENDING, function (stream) { ... }).on(STREAM_STATUS.PLAYING, function (stream) { ... }).on(STREAM_STATUS.STOPPED, function () { ... }).on(STREAM_STATUS.FAILED, function(stream) { $("#preloader").hide(); setStatus(STREAM_STATUS.FAILED, stream); onStopped(); tryToRestart(); }).on(STREAM_STATUS.NOT_ENOUGH_BANDWIDTH, function(stream){ ... }); stream.play(); }
-
Add the function to enable reconnection timer
function tryToRestart() { if (restart) { restartTimerId = setTimeout(function(){ if (stream && (stream.status() != STREAM_STATUS.PLAYING) && restartCount < restartMaxTimes){ $("#playBtn").click(); restartCount++; } if (restartCount >= restartMaxTimes) { console.log("Tried to restart playback for "+restartMaxTimes+" times with "+restartTimeout+" ms interval, cancelled"); } },restartTimeout); } }
-
Add the function to clear reconnection timer
Ready to use samples¶
Ready to use Player example based on WebSDK 2.0.228 can be downloaded here
Ready to use Embed Player example based on WebSDK 2.0.228 can be downloaded here