Compartilhar via


Início rápido: transmitindo uma apresentação de slides usando Reproduzir em (HTML)

[ Este artigo destina-se aos desenvolvedores do Windows 8.x e do Windows Phone 8.x que escrevem aplicativos do Windows Runtime. Se você estiver desenvolvendo para o Windows 10, consulte documentação mais recente ]

Você pode usar Reproduzir em para permitir que os usuários executem facilmente o streaming de áudio, vídeo ou imagens, de seus computadores para dispositivos nas redes domésticas. Este tópico mostra como usar o recurso Reproduzir em no aplicativo da Windows Store para permitir que os usuários transmitam imagens como uma apresentação de slides para um dispositivo de destino.

Objetivo: Use Reproduzir em para transmitir de imagens como uma apresentação de slides para um dispositivo de destino.

Pré-requisitos

Microsoft Visual Studio

Instruções

1. Criar um novo projeto e permitir o acesso às Imagens

  1. Abra o Visual Studio e selecione Novo Projeto no menu Arquivo. Na seção Javascript, selecione Aplicativo em Branco. Nomeie o aplicativo PlayToSlideShow e clique em OK.
  2. Abra o arquivo Package.appxmanifest e selecione a guia Recursos. Selecione a funcionalidade Imagens para habilitar o acesso do seu aplicativo à pasta Imagens em um computador. Feche e salve o arquivo de manifesto.

2. Adicionar a interface do usuário em HTML

Abra o arquivo Default.html e adicione o HTML a seguir à seção <body>. A interface do usuário contém um <div> usado para exibir as imagens e outro usado para exibir mensagens de status. A interface do usuário também contém um <div> que informa ao usuário como começar o streaming usando Reproduzir em e um botão para habilitar o usuário a se desconectar durante o streaming. Esses dois elementos ficam ocultos e se tornam visíveis dependendo de a apresentação de slides ser streaming ou não.

<div id="slideshowDiv" style="height:600px;display:table-cell;vertical-align:bottom;"></div>
<div id="messageDiv">Slideshow disconnected</div>
<button id="disconnectButton" style="width:600px;height:60px;display: none">
    Connected to <img id="iconImage" style="width: 30px;" /> <span id="deviceSpan" />
</button>
<div id="instructionsDiv">Swipe from the right edge of the screen, select "Devices", and select a device to stream the slide show to.</div>

3. Adicione o código de inicialização

O código nessa etapa começa a apresentação de slides e cria o manipulador para o evento de clique do botão de desconexão. O código também inclui uma função de atalho, id, para oferecer acesso conveniente à função getElementById.

Abra a pasta js. Abra o arquivo Default.js e adicione o código a seguir no lugar da função onactivated padrão.

app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {

        startSlideShow();

        args.setPromise(WinJS.UI.processAll());
    }
};

// Disconnect button event handler.
function disconnectButtonClick() {
    Windows.Media.PlayTo.PlayToManager.showPlayToUI();
}

// Shortcut function.
function id(tagName) {
    return document.getElementById(tagName);
}

4. Adicionar código para obter e exibir as imagens como uma apresentação de slides

Este exemplo exibe imagens como uma apresentação de slides usando as imagens na pasta raiz das Imagens. Para fazer isso, primeiro obtenha a lista de imagens da pasta Imagens e depois crie objetos <image> para realizar um ciclo pela lista.

Ao fazer streaming das imagens usando Reproduzir em, o código desse aplicativo de apresentação de slides usa a capacidade de armazenar em buffer o próximo item de mídia usando Reproduzir em. Isso é opcional, mas é útil em cenários nos quais é necessário tempo adicional para a obtenção do próximo item de mídia a ser transmitido. Armazenando a mídia em buffer, você pode transmiti-la imediatamente após a conclusão do item de mídia atual e evitar atrasos entre itens de mídia.

Para armazenar o próximo item de mídia em buffer, definimos a origem do Reproduzir em do item seguinte como a propriedade next do item atual. Quando o item atual é concluído, chamamos o método playNext do item atual para transmitir a próxima origem de mídia para o dispositivo de destino.

Quando a apresentação de slides está sendo reproduzida apenas localmente, o código usa um tempo limite para se mover para a próxima imagem na lista. Quando a apresentação de slides faz streaming para um receptor Reproduzir em, o código ainda usa um tempo limite para se mover para a próxima imagem, mas também responde quando o receptor Reproduzir em pausa a apresentação de slides, move-se para a próxima imagem antes de se esgotar o tempo limite ou é desconectado. Para fazer isso, use o evento statechanged da origem de Reproduzir em referenciada pela propriedade msPlayToSource de um objeto de imagem. No evento statechanged, o código examina as propriedades currentState e previousState dos argumentos passados para o evento. Os diferentes estados, juntamente com o número que identifica o índice da imagem que gerou o evento statechanged, informam como responder conforme mostrado na tabela a seguir.

currentState Ação a ser tomada
desconectado

Se o índice da imagem que gerou o evento for o mesmo índice da imagem que está sendo exibida no momento, isso significará que a origem de Reproduzir em foi desconectada enquanto uma imagem estava sendo exibida. Isso significa que o receptor Reproduzir em não está mais conectado e que iniciamos a apresentação de slides localmente usando o índice de imagem mais recente. Caso contrário, um estado de disconnected simplesmente indica que a apresentação de slides concluiu a exibição da imagem que gerou o evento e que podemos limpar o objeto de imagem que não é mais necessário.

conectado

Se o estado anterior for disconnected, isso significará que a imagem que gerou o evento acabou de ser conectada a um receptor Reproduzir em. Nesse momento, obtemos a próxima imagem para que seja carregada enquanto a imagem atual é exibida.

Se o estado anterior for rendering, isso significará que o usuário pausou a apresentação de slides no receptor Reproduzir em e que limpamos o tempo limite atual até que o usuário reinicie a apresentação.

renderização Se o estado anterior for connected, isso significará que o receptor Reproduzir em cancelou a pausa da apresentação de slides e que podemos iniciá-la novamente.

 

No arquivo Default.js, acrescente o seguinte código após o código da etapa anterior.

var states = Windows.Media.PlayTo.PlayToConnectionState, // alias for PlayToConnectionState
    imageList,               // contains the list of images to show
    streaming = false,       // true when streaming using Play To; otherwise false
    cancel = 0,              // used to cancel a timeout
    timeLapse = 5,           // time between images (5 seconds)
    imageSize = "600px",     // size of current displayed image
    thumbnailSize = "200px", // size of "thumbnail" of next image
    currentImage = 0;        // index of the current image from imageList

// Get the list of images from the Pictures folder and start the slide show.

function startSlideShow() {
    Windows.Storage.KnownFolders.picturesLibrary.getFilesAsync().then(
        function (resultsLibrary) {
            imageList = resultsLibrary;
            if (imageList.length > 0) {
                var image = queueImage(0, true);
            } else {
                id("messageDiv").innerHTML = "There are no images in the Pictures library.";
            }
        });
}


// playNextImage
// Called when a new image is displayed due to a timeout.
// Removes the current image object and queues a new next image.
// Sets the next image index as the new current image, and increases the size 
// of the new current image. Then sets the timeout to display the next image.

function playNextImage(num) {
    id("slideshowDiv").removeChild(id("image" + num));
    queueImage(num + 2, false);

    currentImage = num + 1;
    id("image" + currentImage).style.width = imageSize;

    cancel = setTimeout(function () {
        playNextImage(num + 1);
    }, timeLapse * 1000);
}


// queueImage
// Called to create an image object for the displayed images.

function queueImage(num, isFirstImage) {

    // Create the image element for the specified image index and add to the
    // slide show div.

    var image = document.createElement("img");
    image.style.width = (isFirstImage ? imageSize : thumbnailSize);
    image.id = "image" + num;
    image.src = URL.createObjectURL(imageList[num % imageList.length], { oneTimeOnly: true });
    id("slideshowDiv").appendChild(image);

    // If this is the first image of the slide show, queue the next image. Do
    // not queue if streaming as images are already queued before
    // streaming using Play To.

    if (isFirstImage && !streaming) {

        queueImage(num + 1, false);

        cancel = setTimeout(function () {
            playNextImage(num);
        }, timeLapse * 1000);            
    }

    // Use the transferred event of the Play To connection for the current image object
    // to "move" to the next image in the slide show. The transferred event occurs
    // when the PlayToSource.playNext() method is called, or when the Play To
    // Receiver selects the next image.

    image.msPlayToSource.connection.addEventListener("transferred", function () {

        currentImage = num + 1;
        id("image" + currentImage).style.width = imageSize;

    }, false);


    // Use the statechanged event to determine which action to take or to respond
    // if the Play To Receiver is disconnected.
    image.msPlayToSource.connection.addEventListener("statechanged", function (e) {

        switch (e.currentState) {
            case states.disconnected:

                // If the state is disconnected and the current image index equals the 
                // num value passed to queueImage, then the image element is not connected 
                // to the Play To Receiver any more. Restart the slide show.
                // Otherwise, the current image has been discarded and the slide show
                // has moved to the next image. Clear the current image object and
                // remove it from the slide show div.

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow disconnected";

                    // Cancel any existing timeout
                    if (cancel) {
                        clearTimeout(cancel);
                    }

                    // Clear all image objects from the slide show div
                    while (id("slideshowDiv").firstChild) {
                        id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
                    }

                    // Reset the slide show objects and values to their beginning state
                    streaming = false;
                    id("disconnectButton").style.display = "none";
                    id("instructionsDiv").style.display = "block";
                    disconnectButton.removeEventListener("click", disconnectButtonClick, false);

                    // Restart the slide show from the current image index
                    queueImage(currentImage, true);
                } else {
                    image.msPlayToSource.next = null;
                    image.removeAttribute("src");

                    if (streaming) {
                        id("slideshowDiv").removeChild(image);
                    }
                }

                break;
                
            case states.connected:

                // If the state is connected and the previous state is disconnected, 
                // then the image element is newly connected. Queue up the next image so 
                // that it is loaded while the current image is being displayed.
                // If the previous state is rendering, then the user has paused the slideshow 
                // on the Play To Receiver. Clear the current timeout until the user restarts
                // the slide show.

                if (e.previousState === states.disconnected) {
                    var imageNext = queueImage(num + 1, false);
                    image.msPlayToSource.next = imageNext.msPlayToSource;
                } else if (e.previousState === states.rendering) {
                    if (cancel) {
                        clearTimeout(cancel);
                        cancel = 0;
                    }
                }

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow connected";
                }

                break;

            case states.rendering:

                // If the state is rendering and the previous state is
                // connected, then the Play To Receiver has restarted
                // the slide show.

                if (e.previousState === states.connected) {

                    // Clear any existing timeout.
                    if (cancel) {
                        clearTimeout(cancel);
                    }

                    // Restart the slide show.
                    cancel = setTimeout(function () {
                        image.msPlayToSource.playNext();
                    }, timeLapse * 1000);
                }

                if (currentImage == num) {
                    id("messageDiv").innerHTML = "Slideshow rendering";
                }

                break;
        }

    }, false);

    return image;
}

5. Adicione o código de Reproduzir em

O código nesta etapa implementa o contrato do botão Reproduzir em Ele obtém uma referência ao PlayToManager para o aplicativo atual e associa o manipulador de eventos para os eventos sourcerequested e sourceselected.

Como objetos de imagem são criados e eliminados para cada imagem da apresentação de slides, usamos um objeto de imagem temporário que nunca é eliminado no evento sourcerequested. Isso é feito porque não sabemos se o tempo limite se esgotará antes de o usuário escolher um receptor Reproduzir em. Se isso ocorresse, a imagem atual seria eliminada e passaríamos uma referência nula para Reproduzir em. Em vez disso, passamos para Reproduzir em uma referência a um objeto de imagem que nunca é eliminado e atualizamos a origem da imagem para a imagem exibida atualmente depois que o usuário escolhe um receptor Reproduzir em. Sabemos que isso ocorreu quando o estado da imagem muda para connected.

No arquivo Default.js, acrescente o seguinte código após o código da etapa anterior.

// Set up the Play To contract.

// Used to pass an image to Play To that will not be removed/destroyed
// by the slide show logic. For example, if the user opens the Devices
// charm and the sourcerequested event fires, but the image display timeout
// completes before the user selects a target device, then the image that
// was being displayed is removed and destroyed. intialImage is never 
// destroyed so Play To will always have a valid source to stream.
var initialImage = null;

var ptm = Windows.Media.PlayTo.PlayToManager.getForCurrentView();

ptm.addEventListener("sourcerequested", function (e) {
    initialImage = document.createElement("img");

    // Use the statechanged event of the image passed to Play To to determine when
    // the image is finally connected to the Play To Receiver.
    initialImage.msPlayToSource.connection.addEventListener("statechanged", function (e) {

        if (e.currentState === states.connected) {

            // Clear any existing timeout.
            if (cancel) {
                clearTimeout(cancel);
                cancel = 0;
            }

            // Clear the slide show div.
            while (id("slideshowDiv").firstChild) {
                id("slideshowDiv").removeChild(id("slideshowDiv").firstChild);
            }

            // Set the slide show objects and values to show that we are streaming.
            streaming = true;
            id("disconnectButton").style.display = "block";
            id("instructionsDiv").style.display = "none";

            // Queue and display the next image.
            var image = queueImage(currentImage, true);
            initialImage.msPlayToSource.next = image.msPlayToSource;
            initialImage.msPlayToSource.playNext();
        }
    }, false);

    // Provide Play To with the first image to stream.
    e.sourceRequest.setSource(initialImage.msPlayToSource);

}, false);

// Update the once the user has selected a device to stream to.
ptm.addEventListener("sourceselected", function (e) {
    disconnectButton.addEventListener("click", disconnectButtonClick, false);
    id("messageDiv").innerHTML = "Streaming to " + e.friendlyName + "...";
    id("deviceSpan").innerHTML = e.friendlyName + ".<br/>Click here to disconnect.";
    id("iconImage").src = URL.createObjectURL(e.icon, { oneTimeOnly: true });
}, false);

6. Crie um destino para Reproduzir em (opcional)

Para executar o aplicativo, você precisará de um dispositivo para o qual Reproduzir em possa transmitir mídia. Caso você não possua um receptor Reproduzir em certificado, poderá usar o Windows Media Player como dispositivo de destino. Para isso, seu computador deve estar conectado a uma rede privada. O Windows Media Player precisa estar em execução em um computador diferente do aplicativo de origem de Reproduzir em.

  1. Inicie o Windows Media Player.
  2. Expanda o menu Transmissão e habilite a opção Permitir controle remoto do meu Player. Deixe o Windows Media Player aberto; é necessário que ele esteja em execução para que fique disponível como o destino de Reproduzir em.
  3. Abra o painel de controle Dispositivos e Impressoras. Clique em Adicionar dispositivos e impressoras. No assistente Adicionar dispositivos e impressoras, na janela Escolha um dispositivo ou impressora para adicionar a este PC, localize o Renderizador de mídia digital para o seu PC. Esse é o Windows Media Player para o seu PC. Selecione o item e clique em Avançar. Quando o assistente for concluído, você verá a sua instância do Windows Media Player na lista de Dispositivos Multimídia.

7. Executar o aplicativo

  • No Visual Studio, pressione F5 (depurar) para executar o aplicativo. Você pode selecionar qualquer botão de mídia para reproduzir ou visualizar o primeiro item de mídia em bibliotecas de mídia diferentes. Enquanto uma mídia estiver em reprodução, abra o botão Dispositivos e selecione o destino de Reproduzir em para fazer o streaming da mídia para o dispositivo de destino.

Resumo

Neste guia de início rápido, você adicionou o recurso Reproduzir em a um aplicativo que exibe imagens como uma exibição de slides em um dispositivo de destino. O recurso Reproduzir em permite que os usuários transmitam o conteúdo do aplicativo para um receptor Reproduzir em de sua rede.

Tópicos relacionados

Transmitindo mídia para dispositivos usando Reproduzir em

Exemplos

exemplo do botão Reproduzir em

exemplo de PlayToReceiver

exemplo de Servidor de Mídia