2012-01-23 7 views
15

Questo codice funziona perfettamente con i browser DESKTOP (codice per gentile concessione di @ Rob-W), fai clic sulla miniatura e il video adiacente verrà riprodotto utilizzando l'API di YouTube.L'API di YouTube non funziona con iPad/iPhone/dispositivo non Flash

HTML

<div id="tabs2"> 
    <div> 
    <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'> 
    <iframe id="frame1" width="640" height="390" frameborder="0" title="YouTube video player"type="text/html"src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe> 
    </div> 

    <div> 
     <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'> 
    <iframe id="frame2" width="640" height="390" frameborder="0" title="YouTube video player"type="text/html"src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe> 
    </div> 
</div> 

CSS

#tabs2 div { 
    position: relative; 
} 
/* For security reasons, an element cannor be placed over a frame */ 
/*.thumb { 
    position: absolute; 
}*/  
.play { 
    border: 3px solid red; 
} 

JS

function getFrameID(id) { 
    var elem = document.getElementById(id); 
    if (elem) { 
     if (/^iframe$/i.test(elem.tagName)) return id; //Frame, OK 
     // else: Look for frame 
     var elems = elem.getElementsByTagName("iframe"); 
     if (!elems.length) return null; //No iframe found, FAILURE 
     for (var i = 0; i < elems.length; i++) { 
      if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break; 
     } 
     elem = elems[i]; //The only, or the best iFrame 
     if (elem.id) return elem.id; //Existing ID, return it 
     // else: Create a new ID 
     do { //Keep postfixing `-frame` until the ID is unique 
      id += "-frame"; 
     } while (document.getElementById(id)); 
     elem.id = id; 
     return id; 
    } 
    // If no element, return null. 
    return null; 
} 

// Define YT_ready function. 
var YT_ready = (function() { 
    var onReady_funcs = [], 
     api_isReady = false; 
/* @param func function  Function to execute on ready 
     * @param func Boolean  If true, all qeued functions are executed 
     * @param b_before Boolean If true, the func will added to the first 
            position in the queue*/ 
    return function(func, b_before) { 
     if (func === true) { 
      api_isReady = true; 
      for (var i = 0; i < onReady_funcs.length; i++) { 
       // Removes the first func from the array, and execute func 
       onReady_funcs.shift()(); 
      } 
     } 
     else if (typeof func == "function") { 
      if (api_isReady) func(); 
      else onReady_funcs[b_before ? "unshift" : "push"](func); 
     } 
    } 
})(); 
// This function will be called when the API is fully loaded 

function onYouTubePlayerAPIReady() { 
    YT_ready(true) 
} 

var players = {}; 
//Define a player storage object, to enable later function calls, 
// without having to create a new class instance again. 
YT_ready(function() { 
    $(".thumb + iframe[id]").each(function() { 
     var identifier = this.id; 
     var frameID = getFrameID(identifier); 
     if (frameID) { //If the frame exists 
      players[frameID] = new YT.Player(frameID, { 
       events: { 
        "onReady": createYTEvent(frameID, identifier) 
       } 
      }); 
     } 
    }); 
}); 

// Returns a function to enable multiple events 
function createYTEvent(frameID, identifier) { 
    return function (event) { 
     var player = players[frameID]; // player object 
     var the_div = $('#'+identifier).parent(); 
     the_div.children('.thumb').click(function() { 
      var $this = $(this); 
      $this.fadeOut().next().addClass('play'); 
      if ($this.next().hasClass('play')) { 
       player.playVideo(); 
      } 
     }); 
    } 
} 
// Load YouTube Frame API 
(function(){ //Closure, to not leak to the scope 
    var s = document.createElement("script"); 
    s.src = "http://www.youtube.com/player_api"; /* Load Player API*/ 
    var before = document.getElementsByTagName("script")[0]; 
    before.parentNode.insertBefore(s, before); 
})(); 

JSFiddle

Il problema è che non riesce a giocare su dispositivi iOS (a causa della mancanza di Flash Player, penso, si blocca solo).

Posso forzarlo a suonare toccando il video ancora una volta, cosa che lo richiede di giocare usando QuickTime.

Ma come faccio a giocare automaticamente con QuickTime?

+0

Nota: stopPlayer() sembra funzionare, tuttavia non riesco a riavviare la riproduzione dopo che l'ho interrotta !!! suona per 1/2 secondo e si ferma di sua iniziativa –

risposta

27

Mi dispiace dire che questo non è possibile in iOS. Secondo Apple's documentation,

"... i media incorporati non possono essere riprodotti automaticamente in Safari su iOS - l'utente avvia sempre la riproduzione."

La restrizione è coerente indipendentemente dalla connessione di rete in quanto è una decisione sia per la larghezza di banda che per l'esperienza dell'utente.

aggiornamento, Ottobre 2016: Vale la pena notare, ora che iOS 10 è fuori e guadagnando importanti quote di mercato, che le persone possono sfruttare i cambiamenti nel modo di riproduzione video funziona su iOS 10 per ottenere un comportamento autoplay. Se il video non ha tracce audio o il tag è disattivato, è possibile eseguire la riproduzione automatica. Ulteriori informazioni sono disponibili in this webkit blog. L'API di YouTube potrebbe gestirlo molto presto.

+0

Grazie Tegeril, ho il sospetto che tu abbia ragione. Ti assegnerò la taglia se nessun altro risponde tra qualche giorno. Ho un'altra domanda simile a questa, pensi di poter rispondere anche a questo? Molte grazie http://stackoverflow.com/questions/9033080/youtube-wmode-opaque-not-working-in-ie9-or-any-other-ie – SparrwHawk

+0

Ho trovato un altro riferimento pochi minuti fa, ma poi è andato in crash il mio browser. C'è una discussione su YouTube da qualche parte alla fine confermando che questo è il caso :( – Aaron

+0

qualsiasi video HTML html funzionerà solo dopo l'inizializzazione dell'utente.questo è come stanno le cose per ora. – amit

-4

È possibile utilizzare YouTube iFrame API su iOS.

+0

Sta usando l'API iFrame di YouTube. Transizione riuscita da YouTube Chrome all'icona di riproduzione iOS nativa, ma quell'API non avvia effettivamente la riproduzione. – Aaron

3

A partire da iOS 4, è la proprietà mediaPlaybackRequiresUserAction. Non riesco a capire se la stai implementando sul Web o in un'app nativa, ma impostarla su NO in un'app nativa dovrebbe consentire l'esecuzione della riproduzione automatica.

+1

Ciao Jeff, è puramente sul web, come mostrato sul JSFiddle che ho postato. Potresti mostrarmi come implementarlo usando il violino? Grazie – SparrwHawk

+1

Non puoi se è sul web; questo si applica solo alle app native. –

+0

quindi in pratica si dice che se si incorporasse il safari nella propria app, si potrebbe avere l'auto-riproduzione multimediale. quindi Chrome per iPad potrebbe impostare questo a false se volessero - ma sembra che non lo facessero –

Problemi correlati