mozilla

Revision 270451 of Usar audio y vídeo en Firefox

  • Enlace amigable (slug) de la revisión: Usar_audio_y_vídeo_en_Firefox
  • Título de la revisión: Usar audio y vídeo en Firefox
  • Id de la revisión: 270451
  • Creada:
  • Creador: StripTM
  • ¿Es la revisión actual? No
  • Comentario 7 words added, 8 words removed
Etiquetas: 

Contenido de la revisión

{{ gecko_minversion_header("1.9.1") }}

Firefox 3.5 implementa por primera vez los elementos de HTML 5 audio y video, ofrece la posibilidad de incrustar fácilmente contenido multimedia dentro de documentos HTML. Actualmente, sólo maneja los formatos multimedia Ogg y WAV, pero se espera que en el futuro llege el apoyo de otros formatos.

Incrustar medios

Incrustar medios en tu documento HTML es algo trivial:

<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" autoplay>
  Tu navegador no permite el uso del elemento <code>video</code>.
</video>

Este ejemplo muestra un vídeo de prueba de la web de Theora, por ejemplo.

Es posible especificar múltiples fuentes de ficheros utilizando el elemento source para proporcionar vídeo/audio codificado en distintos formatos para difertes navegadores. Por ejemplo:

<video autoplay>
  <source src="foo.ogg" type="video/ogg">
  <source src="foo.mov">
  Tu navegador no permite el uso del elemento <code>video</code>.
</video>

puede mostrar el fichero OGG a para los navegadores que permiten el uso del formato Ogg. Si el navegador no permite Ogg entonces debería intentar utilizar el fichero MOV.

Nota: El elemento source no está totalmente implementado en Firefox por ahora. Mira {{ bug("449363") }} para más detalles.

Controlar la reproducción de medio

Una vez tienes incrustado un medio en el documento HTML utilizando los nuevos elementos, puedes controlarlo programáticamente desde tu código JavaScript.  Por ejemplo, para arrancar (o volver a arrancar) el vídeo, puedes hacer esto:

var v = document.getElementsByTagName("video")[0];
v.play();

La primera línea obtiene el primer elemento video del documento, y la segunda llama al método play() del elemento, como está definido en la {{ interface("nsIDOMHTMLMediaElement") }} interfaz que se utiliza para aplicar a los elementos multimedia.

Eventos multimedia

Distintos eventos se lanzan cuando se manejan medios:

Nombre del evento Descripción
abort Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent.
canplay Sent when enough data is available that the media can be played, at least for a couple of frames.  This corresponds to the CAN_PLAY readyState.
canplaythrough Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level.
canshowcurrentframe The current frame has loaded and can be presented.  This corresponds to the CAN_SHOW_CURRENT_FRAME readyState.
dataunavailable Sent when the ready state changes to DATA_UNAVAILABLE.
durationchange The metadata has loaded or changed, indicating a change in duration of the media.  This is sent, for example, when the media has loaded enough that the duration is known.
emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
empty Sent when an error occurs and the media is empty.
ended Sent when playback completes.
error Sent when an error occurs.  The element's error attribute contains more information.
load The media has been completely retrieved.
loadedfirstframe The first frame of the media has finished loading.
loadedmetadata The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.
loadstart Sent when loading of the media begins.
pause Sent when playback is paused.
play Sent when playback starts or resumes.
ratechange Sent when the playback speed changes.
seeked Sent when a seek operation completes.
seeking Sent when a seek operation begins.
timeupdate The time indicated by the element's currentTime attribute has changed.
volumechange Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed).
waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).

You can easily watch for these events, using code such as the following:

var v = document.getElementsByTagName("video")[0];

v.addEventListener("seeked", function() { document.getElementsByTagName("video")[0].play(); }, true);
v.currentTime = 10.0;

This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes.  The listener simply calls the element's play() method, which starts playback.

Then, in line 4, the example sets the element's currentTime attribute to 10.0, which initiates a seek operation to the 10-second mark in the media.  This causes a seeking event to be sent when the operation begins, then a seeked event to be dispatched when the seek is completed.

In other words, this example seeks to the 10-second mark in the media, then begins playback as soon as that's finished.

Fallback options

HTML included between, for example, the <video> and </video> is processed by browsers that don't support HTML 5 media. You can take advantage of this fact to provide alternative fallback media for those browsers.

This section provides two possible fallback options for video. In each case, if the browser supports HTML 5 video, that is used; otherwise, the fallback option is used.

Using Flash

You can use Flash to play a Flash format movie if the video element isn't supported:

<video src="video.ogv" controls>
    <object data="flvplayer.swf" type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
      <param value="flvplayer.swf" name="movie"/>
    </object>
</video>

Playing Ogg videos using a Java applet

There's a Java applet called Cortado that you can use as a fallback to play Ogg videos in browsers that have Java support but don't support HTML 5 video:

<video src="my_ogg_video.ogg" controls>
  <applet code="com.fluendo.player.Cortado.class" archive="cortado.jar"
          width="320" height="240">
    <param name="url" value="my_ogg_video.ogg"></param>
  </applet>
</video>

See also

 

 {{ languages( { "fr": "fr/Utilisation_d'audio_et_video_dans_Firefox" } ) }}

 {{ languages( { "es": "es/Etiquetas audio y video en Firefox" } ) }}

Fuente de la revisión

<p>{{ gecko_minversion_header("1.9.1") }}</p>
<p>Firefox 3.5 implementa por primera vez los elementos de HTML 5 <a class="internal" href="/En/HTML/Element/Audio" title="En/HTML/Element/Audio"><code>audio</code></a> y <a class="internal" href="/En/HTML/Element/Video" title="En/HTML/Element/Video"><code>video</code></a>, ofrece la posibilidad de incrustar fácilmente contenido multimedia dentro de documentos HTML. Actualmente, sólo maneja los formatos multimedia Ogg y WAV, pero se espera que en el futuro llege el apoyo de otros formatos.</p>
<h2>Incrustar medios</h2>
<p>Incrustar medios en tu documento HTML es algo trivial:</p>
<pre class="brush: html">&lt;video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" autoplay&gt;
  Tu navegador no permite el uso del elemento &lt;code&gt;video&lt;/code&gt;.
&lt;/video&gt;
</pre>
<p>Este ejemplo muestra un vídeo de prueba de la web de Theora, por ejemplo.</p>
<p>Es posible especificar múltiples fuentes de ficheros utilizando el elemento <a class="internal" href="/En/HTML/Element/Source" title="En/HTML/Element/Source"><code>source</code></a> para proporcionar vídeo/audio codificado en distintos formatos para difertes navegadores. Por ejemplo:</p>
<pre class="brush: html">&lt;video autoplay&gt;
  &lt;source src="foo.ogg" type="video/ogg"&gt;
  &lt;source src="foo.mov"&gt;
  Tu navegador no permite el uso del elemento &lt;code&gt;video&lt;/code&gt;.
&lt;/video&gt;
</pre>
<p>puede mostrar el fichero OGG a para los navegadores que permiten el uso del formato Ogg. Si el navegador no permite Ogg entonces debería intentar utilizar el fichero MOV.</p>
<div class="note"><strong>Nota: </strong>El elemento source no está totalmente implementado en Firefox por ahora. Mira {{ bug("449363") }} para más detalles.</div>
<h2>Controlar la reproducción de medio</h2>
<p>Una vez tienes incrustado un medio en el documento HTML utilizando los nuevos elementos, puedes controlarlo programáticamente desde tu código JavaScript.  Por ejemplo, para arrancar (o volver a arrancar) el vídeo, puedes hacer esto:</p>
<pre class="brush: js">var v = document.getElementsByTagName("video")[0];
v.play();
</pre>
<p>La primera línea obtiene el primer elemento video del documento, y la segunda llama al método <a class="external" href="/En/NsIDOMHTMLMediaElement#play()" title="https://developer.mozilla.org/editor/fckeditor/core/editor/En/NsIDOMHTMLMediaElement#play()"><code>play()</code></a> del elemento, como está definido en la {{ interface("nsIDOMHTMLMediaElement") }} interfaz que se utiliza para aplicar a los elementos multimedia.</p>
<h2>Eventos multimedia</h2>
<p>Distintos eventos se lanzan cuando se manejan medios:</p>
<table class="standard-table"> <tbody> <tr> <td class="header">Nombre del evento</td> <td class="header">Descripción</td> </tr> <tr> <td><code>abort</code></td> <td>Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent.</td> </tr> <tr> <td><code>canplay</code></td> <td>Sent when enough data is available that the media can be played, at least for a couple of frames.  This corresponds to the <code>CAN_PLAY</code> <code>readyState</code>.</td> </tr> <tr> <td><code>canplaythrough</code></td> <td>Sent when the ready state changes to <code>CAN_PLAY_THROUGH</code>, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level.</td> </tr> <tr> <td><code>canshowcurrentframe</code></td> <td>The current frame has loaded and can be presented.  This corresponds to the <code>CAN_SHOW_CURRENT_FRAME</code> <code>readyState</code>.</td> </tr> <tr> <td><code>dataunavailable</code></td> <td>Sent when the ready state changes to <code>DATA_UNAVAILABLE</code>.</td> </tr> <tr> <td><code>durationchange</code></td> <td>The metadata has loaded or changed, indicating a change in duration of the media.  This is sent, for example, when the media has loaded enough that the duration is known.</td> </tr> <tr> <td><code>emptied</code></td> <td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a class="internal" href="/En/nsIDOMMediaHTMLElement#load()" title="En/nsIDOMMediaHTMLElement#load()"><code>load()</code></a> method is called to reload it.</td> </tr> <tr> <td><code>empty</code></td> <td>Sent when an error occurs and the media is empty.</td> </tr> <tr> <td><code>ended</code></td> <td>Sent when playback completes.</td> </tr> <tr> <td><code>error</code></td> <td>Sent when an error occurs.  The element's <code>error</code> attribute contains more information.</td> </tr> <tr> <td><code>load</code></td> <td>The media has been completely retrieved.</td> </tr> <tr> <td><code>loadedfirstframe</code></td> <td>The first frame of the media has finished loading.</td> </tr> <tr> <td><code>loadedmetadata</code></td> <td>The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.</td> </tr> <tr> <td><code>loadstart</code></td> <td>Sent when loading of the media begins.</td> </tr> <tr> <td><code>pause</code></td> <td>Sent when playback is paused.</td> </tr> <tr> <td><code>play</code></td> <td>Sent when playback starts or resumes.</td> </tr> <tr> <td><code>ratechange</code></td> <td>Sent when the playback speed changes.</td> </tr> <tr> <td><code>seeked</code></td> <td>Sent when a seek operation completes.</td> </tr> <tr> <td><code>seeking</code></td> <td>Sent when a seek operation begins.</td> </tr> <tr> <td><code>timeupdate</code></td> <td>The time indicated by the element's <code>currentTime</code> attribute has changed.</td> </tr> <tr> <td><code>volumechange</code></td> <td>Sent when the audio volume changes (both when the volume is set and when the <code>muted</code> attribute is changed).</td> </tr> <tr> <td><code>waiting</code></td> <td>Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).</td> </tr> </tbody>
</table>
<p>You can easily watch for these events, using code such as the following:</p>
<pre>var v = document.getElementsByTagName("video")[0];

v.addEventListener("seeked", function() { document.getElementsByTagName("video")[0].play(); }, true);
v.currentTime = 10.0;
</pre>
<p>This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes.  The listener simply calls the element's <code>play()</code> method, which starts playback.</p>
<p>Then, in line 4, the example sets the element's <code>currentTime</code> attribute to 10.0, which initiates a seek operation to the 10-second mark in the media.  This causes a <code>seeking</code> event to be sent when the operation begins, then a <code>seeked</code> event to be dispatched when the seek is completed.</p>
<p>In other words, this example seeks to the 10-second mark in the media, then begins playback as soon as that's finished.</p>
<h2>Fallback options</h2>
<p>HTML included between, for example, the <code>&lt;video&gt;</code> and <code>&lt;/video&gt;</code> is processed by browsers that don't support HTML 5 media. You can take advantage of this fact to provide alternative fallback media for those browsers.</p>
<p>This section provides two possible fallback options for video. In each case, if the browser supports HTML 5 video, that is used; otherwise, the fallback option is used.</p>
<h3>Using Flash</h3>
<p>You can use Flash to play a Flash format movie if the <code>video</code> element isn't supported:</p>
<pre class="brush: html">&lt;video src="video.ogv" controls&gt;
    &lt;object data="flvplayer.swf" type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"&gt;
      &lt;param value="flvplayer.swf" name="movie"/&gt;
    &lt;/object&gt;
&lt;/video&gt;
</pre>
<h3>Playing Ogg videos using a Java applet</h3>
<p>There's a Java applet called <a class="external" href="http://maikmerten.livejournal.com/2256.html" title="http://maikmerten.livejournal.com/2256.html">Cortado</a> that you can use as a fallback to play Ogg videos in browsers that have Java support but don't support HTML 5 video:</p>
<pre class="brush: html">&lt;video src="my_ogg_video.ogg" controls&gt;
  &lt;applet code="com.fluendo.player.Cortado.class" archive="cortado.jar"
          width="320" height="240"&gt;
    &lt;param name="url" value="my_ogg_video.ogg"&gt;&lt;/param&gt;
  &lt;/applet&gt;
&lt;/video&gt;
</pre>
<h2>See also</h2>
<ul> <li><a class="internal" href="/En/HTML/Element/Audio" title="En/HTML/Element/Audio"><code>audio</code></a></li> <li><a class="internal" href="/En/HTML/Element/Video" title="En/HTML/Element/Video"><code>video</code></a></li> <li><a class="internal" href="/En/HTML/Element/Source" title="En/HTML/Element/Source"><code>source</code></a> </li> <li><a class="internal" href="/En/Manipulating_video_using_canvas" title="En/Manipulating video using canvas">Manipulating video using canvas</a></li> <li>{{ interface("nsIDOMHTMLMediaElement") }}</li>
</ul>
<p> </p>
<p> {{ languages( { "fr": "fr/Utilisation_d'audio_et_video_dans_Firefox" } ) }}</p>
<p> {{ languages( { "es": "es/Etiquetas audio y video en Firefox" } ) }}</p>
Revertir a esta revisión