2015-02-11 2 views
0

Я сделал плеер JQuery для изображений Demo Link. Он меняет экраны с предоставленными интервалами и рисует касание. Теперь я хочу реализовать функциональность пэса, играть. При нажатии на кнопку воспроизведения, чтобы остановить воспроизведение экрана, я называю FlowPlaye.stop() метод:JQuery - Image player issue

FlowPlayer.prototype.stop = function() { 
     $(".fp-pause").removeClass("fp-pause").addClass("fp-play"); 
     clearInterval(this.screenIntervalId); 
     clearInterval(this.timeIntervalId); 
     clearInterval(this.touchIntervalId); 
     $('.fp-progress').stop(); 
     this.isAnimated = false; 
     return false; 
    } 

И во второй раз FlowPlayer.play():

FlowPlayer.prototype.play = function() { 
    var fp = this; // Obj refers to the FlowPlayer itself such as "this" 
    fp.isAnimated = true; 
    console.log(typeof this.screenIndex) 
    console.log(this.screenIndex) 

    fp.screenIndex = typeof this.screenIndex == 'number' ? this.screenIndex : 0; 
    fp.render(fp.screens[fp.screenIndex]); 
    fp.initTimeline(fp.duration); 

    fp.screenIntervalId = setInterval(function() { 
     if (fp.screenIndex == fp.screens.length - 1) { 
      console.log("the end of screens"); 
      clearInterval(fp.screenIntervalId) 
      return; 
     } 
     ++fp.screenIndex; 
     fp.render(fp.screens[fp.screenIndex]); 
    }, fp.screens[fp.screenIndex].delay) 


} 

Проблема заключается в том, что, когда я делаю это, экран игры интервалы возились (попытайтесь остановить видео на 20-й секунде и восстановите). Мне нужно сохранить состояние игрока, но я не знаю, как это сделать. Итак, может кто-нибудь помочь мне решить эту проблему?

ответ

0

Я думаю, что использование 3 разных таймеров делает это ненужным. Если вы реорганизуете его на один единый таймер, пауза (и другие элементы управления воспроизведением) будет довольно простой.

  1. Отделить ключевой кадр событий в отдельные функции:

    function setImage(img) {...} 
    function showTouch(x, y) {...} 
    function hideTouch() {...} 
    
  2. При запуске конвертировать screens массив что-то вроде этого:

    var keyframes = [ 
         { time:0, func:setImage, args:['http://...']}, 
         { time:1000, func:showTouch, args:[10, 30]}, 
         { time:3000, func:hideTouch, args:[]}, 
         ... 
        ]; 
    
  3. Настройка один таймер для воспроизведения :

    var time = 0, 
        next = 0, 
        isPaused = false, 
        interval; 
    function timer() { 
        if (isPaused) { 
         return; 
        } 
        var nextKeyframe = keyframes[next]; 
        time += 100; 
        if (time >= nextKeyframe.time) { 
         nextKeyframe.func.apply(this, nextKeyframe.args); 
         next += 1; 
         if (next === keyframes.length) { 
          clearInterval(interval); 
         } 
        } 
    } 
    
  4. Теперь у вас есть легко управляемое воспроизведение:

    // play/replay - reset time and next, then start the timer 
    time = 0; 
    next = 0; 
    interval = setInterval(timer, 100); 
    
    // seek - just set a new time, and find the next keyframe 
    time = 1500; 
    for (next = 0; keyframes[next].time < time && next < keyframes.length; next++) {} 
    
    // pause - the timer stays on, but won't do anything 
    isPaused = true; 
    
    // stop 
    clearInterval(interval); 
    

Примечание: Фрагменты не проверялось, может иметь некоторые опечатки в них. Я просто хотел продемонстрировать, как сделать его более чистым/более контролируемым.

+0

Спасибо за отличный ответ :) – Danis