0

Para reproduzir vídeos do YouTube em uma página da Web com playlist select-option, trago um exemplo simplório:

Código

troca = function (link) { 
    document.getElementById('video').innerHTML = '<iframe src="'+link+'" width="420" height="315" frameborder="0" allowfullscreen></iframe>';
}
select {
    font-size:20px; 
    width:176px; 
    height:100%;
    padding:15px; 
    float: right;
}

option {
    font-size: 10pt;
    padding:10 10 10 10;
    float: left;
    cursor: pointer;
}

span {
    float:left;
}
<span id='video'>&nbsp;</span>

<select onChange="troca(this.options[this.selectedIndex].value);" size="4">
    <option value="https://www.youtube.com/embed/iZUojirTEgM" style="background-image: url(https://img.youtube.com/vi/iZUojirTEgM/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 1</option>
    <option value="https://www.youtube.com/embed/ZEOmtEyXJtU" style="background-image: url(https://img.youtube.com/vi/ZEOmtEyXJtU/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 2</option>
    <option value="https://www.youtube.com/embed/GSzCLf8tjP4" style="background-image: url(https://img.youtube.com/vi/GSzCLf8tjP4/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 3</option>
</select>

Exemplo acima se aplica usando o <iframe> (recomendado)

Antes utilizava object e embed, mas o YouTube <object> e <embed> foram suspensos a partir de janeiro de 2015. Passando a migrar seus vídeos para usar <iframe>.

Bom, agora surgiu uma dúvida.

O interessante da tag <video> é que você pode definir um "fallback" caso o vídeo não consiga ser exibido.

Nesse caso seria ideal exibir até mesmo o vídeo através do Flash.

<video width="420" height="315" src="video.webm" controls>
   <object  width="420" height="315" data="flvplayer.swf" type="application/x-shockwave-flash">
    <embed src="'+link+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="420" height="315">
   <param value="'+link+'" name="movie"/>
</object>

Como poderia acrescentar os elementos video, object e embed a função junto ao select-option como playlist?

4
  • Essa verificação não é o próprio Youtube que faz dentro do iframe? 26/01/2017 às 17:08
  • O que eu quis dizer é que o iframe vai uma página do Youtube. Como no exemplo https://www.youtube.com/embed/iZUojirTEgM. Essa página já não tem um script pra tratar esse tipo de coisa? Tu testou esse iframe em browsers mais antigos? 26/01/2017 às 17:15
  • Ah bom, achei que estivesse com problemas mesmo com o Youtube. 26/01/2017 às 17:30
  • faz um tempo que eu não preciso mexer com videos, mas eu lembro que se o browser não reconhece a tag video ele trata como se fosse div. Então tu pode adicionar no final das tag video o source sendo um player compatível. Vou colocar isso numa resposta pra tu enxergar melhor 26/01/2017 às 17:45

2 Respostas 2

0

Este site fala sobre uma técnica que consiste em usar a tag video normalmente com seus sources, e depois do último source tu adiciona um player em Flash para compatibilidade.


EDIT

Minha resposta inicial não responde adequadamente à pergunta, então para responder melhor a pergunta, fiz um exemplo no JSBin e no CodePen onde eu tenho um viewport para mostrar o vídeo selecionado e uma lista para que o usuário selecione o vídeo.

A ideia principal é que o código consiste em:

  • Um container com todos os vídeos (display: none; por padrão)
  • Uma lista para o usuário escolher os vídeos, onde o link dessa lista aponta para o id do vídeo correspondente. Ex.: <a href="#video-1">Vídeo 1</a>.
  • Um JS escutando o evento de clique dos items da lista cujo trabalho é apenas esconder o vídeo atualmente ativo e mostrar o item selecionado pelo usuário.

Exemplo

$(document).ready(function(){
    // cache do container
    var video_container = $('.playlist-viewport');

    $('.playlist-item').on('click', function(event){
        // pega apenas a hash do link
        var video_id = "#" + this.href.split('#')[1];

        // esconde o vídel atual
        video_container.find('.video.active').removeClass('active');
        
        // mostra o novo video
        $(video_id).addClass('active');

        // evita que o browser siga o link
        event.preventDefault();
        return false;
    });
});
body {
    background-color: #555;
    margin-top: 30px;
}

.playlist-viewport {
    list-style: none;
}

.playlist-viewport > .video {
    display: none;
}

.playlist-viewport > .video.active {
    display: block;
}
<!-- frameworks e bibliotecas -->
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<!-- grid -->
<div class="container">
    <div class="row">
        <div class="col-xs-9">

            <!-- Container para os videos -->
            <ul class="playlist-viewport">
                <!-- Video 1 -->
                <li id="video-1" class="video active">
                    <!-- video responsivo (bootstrap) -->
                        <div class="embed-responsive embed-responsive-16by9">
                            <video class="embed-responsive-item" controls="controls" 
                            poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" >
                                <!-- sources para o player HTML5 -->
                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />

                                <!-- Fallback para player em Flash -->
                                <object type="application/x-shockwave-flash" 
                                    data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" 
                                    width="640" height="360">
                                    
                                    <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
                                    <param name="allowFullScreen" value="true" />
                                    <param name="wmode" value="transparent" />
                                    <param name="flashVars" 
                                        value="config={'playlist':['http%3A%2F%2Fsandbox.thewikies.com%2Fvfe-generator%2Fimages%2Fbig-buck-bunny_poster.jpg',{'url':'http%3A%2F%2Fclips.vorwaerts-gmbh.de%2Fbig_buck_bunny.mp4','autoPlay':false}]}" />
                                    <img alt="Big Buck Bunny" 
                                        src="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" 
                                        width="640" height="360" 
                                        title="No video playback capabilities, please download the video below" />
                                </object>
                            </video>
                    </div>
                </li>

                <li id="video-2" class="video">
                    <div class="embed-responsive embed-responsive-16by9">
                        <video class="embed-responsive-item" controls="controls" >
                            <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
                            <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm> 
                            <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg> 

                            <object type="application/x-shockwave-flash" 
                                data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" 
                                width="640" height="360">
                                
                                <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
                                <param name="allowFullScreen" value="true" />
                                <param name="wmode" value="transparent" />
                                <param name="flashVars" 
                                value="config={'playlist':[{'url ':'http%3A%2F%2Ftechslides.com%2Fdemos%2Fsample-videos%2Fsmall.mp4','autoPlay':false}]}" />
                            </object>
                        </video>
                    </div>
                </li>
            </ul>

        </div>

        <!-- Container da lista de vídeos -->
        <div class="col-xs-3">
            <ul class="list-group">
                <a href="#video-1" class="list-group-item playlist-item">Big Buck Bunny</a>
                <a href="#video-2" class="list-group-item playlist-item">Outro vídeo</a>
            </ul>
        </div>

    </div>
</div>

0
0

Esta rotina apenas verifica se o navegador dá suporte tag video, e direciona uma alternativa.

<script>

// criar o elemento <video>
var video = document.createElement("video");

// acrescentar ao elemento <body>
document.body.appendChild(video);

troca = function (link)
{ 

// criando array com índice do valores do <option>
var array = link.split("|");

if('controls' in video){

document.getElementById('video').innerHTML = [
'<video width="420" height="315" controls>',
   '<source src="'+array[0]+'.mp4" type="video/mp4">',
   '<source src="'+array[0]+'.webm" type="video/webm">',
'</video>'
]

} else {

document.getElementById('video').innerHTML = [
'<object width="420" height="315" data="'+array[1]+'">',
   '<embed width="420" height="315" src="'+array[1]+'">',
   '</embed>',
 '</object>'
]
}
}
</script>

Explicando

Manipulando com JavaScript

Para criar um elemento vídeo, uso a função document.createElement.

Uso o operador "in" para checar se o atributo existe no elemento.

Se existe ou não, a condição aplicará a melhor opção ao navegador.

A variável array, define índice dos valores separado por "|" no value do option

// criar o elemento <video>
var video = document.createElement("video");

// acrescentar ao elemento <body>
document.body.appendChild(video);

troca = function (link)
{ 

// criando array com índice do valores do <option>
var array = link.split("|");

if('controls' in video){

document.getElementById('video').innerHTML = [
'<video width="420" height="315" controls>',
   '<source src="'+array[0]+'.mp4" type="video/mp4">',
   '<source src="'+array[0]+'.webm" type="video/webm">',
'</video>'
]

} else {

document.getElementById('video').innerHTML = [
'<object width="420" height="315" data="'+array[1]+'">',
   '<embed width="420" height="315" src="'+array[1]+'">',
   '</embed>',
 '</object>'
]
}
}
select {
	width:300px; 
	height:100%;
	padding:30px; 
	float: right;
	background-color: #FCFCFC;
}	

option {
	font-size: 12pt;
	color: white;
	padding: 10 10 10 10;
	margin: 0 auto;
	background-repeat: no-repeat; 
	background-position: center; 
	background-size: 196px; 110px;
	width: 196px; 
	height: 110px;
	text-align: center;
}

option:hover { 
	background-color: steelblue; 
	cursor: pointer; 
}
	<span id='video'>&nbsp;</span>

<select id="lista" onChange="troca(this.options[this.selectedIndex].value);" size="4">

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/big_buck_bunny|https://www.youtube.com/embed/yUQM7H4Swgw" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/big_buck_bunny.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/madagascar_2|https://www.youtube.com/embed/y8WJG7lrHCU" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/madagascar_2.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/procurando_dory|https://www.youtube.com/embed/ooSaxz-SHts" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/procurando_dory.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/meu_malvado_favorito_2|https://www.youtube.com/embed/B82b77UA9qY" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/meu_malvado_favorito_2.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/animais_cantando|https://www.youtube.com/embed/qiEwyK7l5uw" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/animais_cantando.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/a_capela_animais|https://www.youtube.com/embed/791zd6qfqoU" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/a_capela_animais.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/monstros_sa_2|https://www.youtube.com/embed/91WYf1fhB9U" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/monstros_sa_2.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/peck_pocketed|https://www.youtube.com/embed/qmCWjjZketo" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/peck_pocketed.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/equipment_these_days|https://www.youtube.com/embed/WxaAhc3jf5s" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/equipment_these_days.jpg);"></option>

	<option value="https://sites.google.com/site/mplayerplugin/repositorio/skate|https://www.youtube.com/embed/Zlv6eSiGl1U" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/skate.jpg);"></option>

</select>

Acesse - demonstração

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .