HTML::Object::DOM::Element::Media - HTML Object DOM Media Class
use HTML::Object::DOM::Element::Media; my $media = HTML::Object::DOM::Element::Media->new || die( HTML::Object::DOM::Element::Media->error, "\n" );
v0.2.0
This interface adds to HTML::Object::DOM::Element the properties and methods needed to support basic media-related capabilities that are common to audio and video.
+-----------------------+ +---------------------------+ +-------------------------+ +----------------------------+ +-----------------------------------+ | HTML::Object::Element | --> | HTML::Object::EventTarget | --> | HTML::Object::DOM::Node | --> | HTML::Object::DOM::Element | --> | HTML::Object::DOM::Element::Media | +-----------------------+ +---------------------------+ +-------------------------+ +----------------------------+ +-----------------------------------+
Inherits properties from its parent HTML::Object::DOM::Element
A AudioTrackList that lists the AudioTrack objects contained in the element.
Example:
my $video = $doc->getElementById("video"); for( my $i = 0; $i < $video->audioTracks->length; $i += 1 ) { $video->audioTracks->[$i]->enabled = 0; # false }
See also Mozilla documentation
A boolean value that reflects the autoplay HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption.
autoplay
Note: Automatically playing audio when the user does not expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. See the Mozilla Autoplay guide for media and Web Audio APIs for more information. Keep in mind that browsers may ignore autoplay requests, so you should ensure that your code is not dependent on autoplay working.
<video id="video" autoplay="" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165"> </video> # *** Disable autoplay (recommended) *** # false is the default value $doc->querySelector('#video')->autoplay = 0; # false # <video id="video" controls>
This returns undef under perl.
undef
Normally, under JavaScript, this returns a TimeRanges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed.
TimeRanges
Normally, under JavaScript, this returns a MediaController object that represents the media controller assigned to the element, or undef if none is assigned.
MediaController
Is a boolean that reflects the controls HTML attribute, indicating whether user interface items for controlling the resource should be displayed.
my $obj = $doc->createElement('video'); $obj->controls = 1; # true
Returns a HTML::Object::TokenList that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The HTML::Object::TokenList takes one or more of three possible values: nodownload, nofullscreen, and noremoteplayback.
nodownload
nofullscreen
noremoteplayback
To disable the dowload button for HTML5 audio and video player:
<audio controls controlsList="nodownload"><source src="song.mp3" type="audio/mpeg"></audio> <video controls controlsList="nodownload"><source src="video.mp4" type="video/mp4"></video>
Another example:
<video controls controlsList="nofullscreen nodownload noremoteplayback"></video>
Using code:
my $video = $doc->querySelector('video'); $video->controls; # true $video->controlsList; # ["nofullscreen", "nodownload", "noremoteplayback"] $video->controlsList->remove('noremoteplayback'); $video->controlsList; # ["nofullscreen", "nodownload"] $video->getAttribute('controlsList'); # "nofullscreen nodownload" # Actually, under perl, 'supports' always returns true $video->controlsList->supports('foo'); # false $video->controlsList->supports('noremoteplayback'); # true
See also Mozilla documentation, Chromium documentation
A string indicating the CORS setting for this media element.
Returns a string with the absolute URL of the chosen media resource.
my $obj = $doc->createElement('video'); say($obj->currentSrc); # ""
This returns whatever number you set it to under perl, as a Module::Generic::Number object.
Normally, under JavaScript, this returns a double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline.
my $video = $doc->createElement('$video'); say( $video->currentTime ); $vide->currentTime = 35;
A Boolean that reflects the muted HTML attribute, which indicates whether the media element's audio output should be muted by default.
muted
my $video = $doc->createElement('video'); $video->defaultMuted = 1; # true say( $video->outerHTML ); # <video muted=""></video>
Normally, under JavaScript, this returns a double indicating the default playback rate for the media.
my $obj = $doc->createElement('video'); say($obj->defaultPlaybackRate); # 1
A boolean that sets or returns the remote playback state of the HTML attribute, indicating whether the media element is allowed to have a remote playback UI.
my $obj = $doc->createElement('audio'); # <audio></audio> $obj->disableRemotePlayback = 1; # true # <audio disableremoteplayback=""></audio>
Normally, under JavaScript, this returns a read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is NaN. If the media is of indefinite length (such as streamed live media, a WebRTC call's media, or similar), the value is +Infinity.
NaN
+Infinity
my $obj = $doc->createElement('video'); say( $obj->duration ); # NaN
Returns a Boolean that indicates whether the media element has finished playing.
my $obj = $doc->createElement('video'); say($obj->ended); # false
Read-only.
This returns a HTML::Object::MediaError object for the most recent error, or undef if there has not been an error.
my $video = $doc->createElement('video'); $video->onerror = sub { say( "Error " . $video->error->code . "; details: " . $video->error->message ); } $video->src = 'https://example.org/badvideo.mp4';
A Boolean that reflects the loop HTML attribute, which indicates whether the media element should start over when it reaches the end.
loop
my $obj = $doc->createElement('video'); $obj->loop = 1; # true
This always returns undef under perl.
Normally, under JavaScript, this returns a MediaKeys object or undef. MediaKeys is a set of keys that an associated HTML::Object::DOM::Element::Media can use for decryption of media data during playback.
Is a boolean that determines whether audio is muted. true if the audio is muted and false otherwise. This does not affect the DOM.
my $obj = $doc->createElement('video'); say( $obj->muted ); # false
Set or get an integer (enumeration) indicating the current state of fetching the media over the network.
<audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> # Export constants use HTML::Object::DOM::Element::Media qw( :all ); my $obj = $doc->getElementById('example'); $obj->addEventListener( playing => sub { if( $obj->networkState == NETWORK_LOADING ) { # Still loading... } });
See "CONSTANTS" below for the constants that can be exported and used.
Returns a boolean that indicates whether the media element is paused. This is set to true if you use the "pause" method and set to false when you use the "play" method.
my $obj = $doc->createElement('video'); say( $obj->paused ); # true
This only sets or gets a number under perl environment.
Normally, under JavaScript, this is a double that indicates the rate at which the media is being played back.
my $obj = $doc->createElement('video'); say( $obj->playbackRate ); # Expected Output: 1
Normally, under JavaScript, this returns a TimeRanges object that contains the ranges of the media source that the browser has played, if any.
Is a string that reflects the preload HTML attribute, indicating what data should be preloaded, if any. Possible values are: none, metadata, auto.
preload
none
metadata
auto
Under perl environment, this is just a boolean value you can set or get.
Under JavaScript environment, this is a boolean that determines if the pitch of the sound will be preserved. If set to false, the pitch will adjust to the speed of the audio. This is implemented with prefixes in Firefox (mozPreservesPitch) and WebKit (webkitPreservesPitch).
mozPreservesPitch
webkitPreservesPitch
Set or get an integer (enumeration) indicating the readiness state of the media.
<audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> use HTML::Object::DOM::Element::Media qw( :all ); my $obj = $doc->getElementById('example'); $obj->addEventListener( loadeddata => sub { if( $obj->readyState >= NETWORK_LOADING ) { $obj->play(); } });
See "CONSTANTS" for the constants that can be exported and used.
Normally, under JavaScript, this returns a TimeRanges object that contains the time ranges that the user is able to seek to, if any.
Under JavaScript environment, this is a boolean that indicates whether the media is in the process of seeking to a new position.
This returns undef by default under perl. You can set a value using "setSinkId".
Normally, under JavaScript, this returns a string that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the MediaDeviceInfo.deviceid values returned from MediaDevices.enumerateDevices(), id-multimedia, or id-communications.
MediaDeviceInfo.deviceid
MediaDevices.enumerateDevices()
Is a string that reflects the src HTML attribute, which contains the URL of a media resource to use.
src
my $obj = $doc->createElement('video'); say( $obj->src ); # ""
Normally, under JavaScript, this is a MediaStream representing the media to play or that has played in the current HTML::Object::DOM::Element::Media, or undef if not assigned.
Returns the list of TextTrack objects contained in the element.
<video controls poster="/images/sample.gif"> <source src="sample.mp4" type="video/mp4"> <source src="sample.ogv" type="video/ogv"> <track kind="captions" src="sampleCaptions.vtt" srclang="en"> <track kind="descriptions" src="sampleDescriptions.vtt" srclang="en"> <track kind="chapters" src="sampleChapters.vtt" srclang="en"> <track kind="subtitles" src="sampleSubtitles_de.vtt" srclang="de"> <track kind="subtitles" src="sampleSubtitles_en.vtt" srclang="en"> <track kind="subtitles" src="sampleSubtitles_ja.vtt" srclang="ja"> <track kind="subtitles" src="sampleSubtitles_oz.vtt" srclang="oz"> <track kind="metadata" src="keyStage1.vtt" srclang="en" label="Key Stage 1"> <track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2"> <track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3"> </video> my $tracks = $doc->querySelector('video')->textTracks; # $tracks->length == 10 for( my $i = 0, $L = $tracks->length; $i < $L; $i++ ) { if( $tracks->[$i]->language eq 'en' ) { say( $tracks->[$i] ); } }
Returns the list of VideoTrack objects contained in the element.
Is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
Inherits methods from its parent HTML::Object::DOM::Element
Adds a text track (such as a track for subtitles) to a media element.
This takes a track kind, label and language and returns a new HTML::Object::DOM::TextTrack object.
kind
label
language
Possible values for kind are:
label is a string specifying the label for the text track. Is used to identify the text track for the users.
language in iso 639 format (e.g. en-US or ja-JP).
en-US
ja-JP
Normally, under JavaScript, given a string specifying a MIME media type (potentially with the codecs parameter included), canPlayType() returns the string probably if the media should be playable, maybe if there's not enough information to determine whether the media will play or not, or an empty string if the media cannot be played.
canPlayType
my $obj = $doc->createElement('video'); say( $obj->canPlayType('video/mp4') ); # "maybe"
Normally, under JavaScript, this returns MediaStream, captures a stream of the media content.
MediaStream
$doc->querySelector('.playAndRecord')->addEventListener( click => sub { my $playbackElement = $doc->getElementById("playback"); my $captureStream = $playbackElement->captureStream(); $playbackElement->play(); });
Normally, under JavaScript, this quickly seeks to the given time with low precision.
my $myVideo = $doc->getElementById("myVideoElement"); $myVideo->fastSeek(20);
Normally, under JavaScript, this resets the media to the beginning and selects the best available source from the sources provided using the src attribute or the <source> element.
my $mediaElem = $doc->querySelector("video"); $mediaElem->load();
Under perl, this does not do anything particular except setting the "paused" boolean value to true.
Pauses the media playback.
This does not do anything in particular under perl, except setting the paused boolean value to false.
paused
Normally, under JavaScript, this begins playback of the media.
use Nice::Try; my $videoElem = $doc->getElementById( 'video' ); my $playButton = $doc->getElementById( 'playbutton' ); $playButton->addEventListener( 'click', \&handlePlayButton, { capture => 0 }); playVideo(); sub playVideo { try { $videoElem->play(); $playButton->classList->add( 'playing' ); } catch($err) { $playButton->classList->remove( 'playing' ); } } sub handlePlayButton { if( $videoElem->paused ) { playVideo(); } else { $videoElem->pause(); $playButton->classList->remove( 'playing' ); } }
Provided with a HTML::Object::DOM::TextTrack object and this will remove it.
It returns the HTML::Object::DOM::TextTrack object upon success, or if it cannot be found, it returns undef
Normally, under JavaScript, this seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.
Normally, under JavaScript, this returns Promise. Sets the MediaKeys keys to use when decrypting media during playback.
This does not do anything particular under perl, except setting the value of "sinkid".
Normally, under JavaScript, this sets the ID of the audio device to use for output and returns a Promise. This only works when the application is authorized to use the specified device.
This is not used under perl, but you can trigger that event yourself.
Under JavaScript, this is fired when the resource was not fully loaded, but not as the result of an error.
my $video = $doc->querySelector('video'); my $videoSrc = 'https://example.org/path/to/video.webm'; $video->addEventListener( abort => sub { say( "Abort loading: ", $videoSrc ); }); my $source = $doc->createElement('source'); $source->setAttribute( src => $videoSrc ); $source->setAttribute( type => 'video/webm' ); $video->appendChild( $source );
Under JavaScript, this is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content
my $video = $doc->querySelector( 'video' ); $video->addEventListener( canplay => sub { my $event = shift( @_ ); say( 'Video can start, but not sure it will play through.' ); }); my $video = $doc->querySelector( 'video' ); $video->oncanplay = sub { my $event = shift( @_ ); say( 'Video can start, but not sure it will play through.' ); };
Under JavaScript, this is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
my $video = $doc->querySelector( 'video' ); $video->addEventListener( canplaythrough => sub { my $event = shift( @_ ); say( "I think I can play through the entire video without ever having to stop to buffer." ); }); my $video = $doc->querySelector( 'video' ); $video->oncanplaythrough = sub { my $event = shift( @_ ); say( "I think I can play through the entire video without ever having to stop to buffer." ); };
This is fired when the duration property has been updated.
my $video = $doc->querySelector('video'); $video->addEventListener( durationchange => sub { say( 'Not sure why, but the duration of the $video has changed.' ); }); my $video = $doc->querySelector('video'); $video->ondurationchange = sub { say( 'Not sure why, but the duration of the video has changed.' ); };
Under JavaScript, this is fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the "load" in HTML::Object::DOM::Element::Media method is called to reload it.
my $video = $doc->querySelector('video'); $video->addEventListener( emptied => sub { say( 'Uh oh. The media is empty. Did you call load()?' ); }); my $video = $doc->querySelector('video'); $video->onemptied = sub { say( 'Uh oh. The media is empty. Did you call load()?' ); };
Under JavaScript, this is fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available.
my $obj = $doc->createElement('video'); say( $obj->ended ); # false
Fired when the resource could not be loaded due to an error.
my $videoElement = $doc->createElement( 'video' ); $videoElement->onerror = sub { say( "Error " . $videoElement->error->code . "; details: " . $videoElement->error->message ); } $videoElement->src = "https://example.org/bogusvideo.mp4";
Under JavaScript, this is fired when the first frame of the media has finished loading.
my $video = $doc->querySelector('video'); $video->addEventListener( loadeddata => sub { say( 'Yay! The readyState just increased to HAVE_CURRENT_DATA or greater for the first time.' ); }); my $video = $doc->querySelector('video'); $video->onloadeddata = sub { say( 'Yay! The readyState just increased to HAVE_CURRENT_DATA or greater for the first time.' ); };
Under JavaScript, this is fired when the metadata has been loaded
my $video = $doc->querySelector('video'); $video->addEventListener( loadedmetadata => sub { say( 'The duration and dimensions of the media and tracks are now known.' ); }); my $video = $doc->querySelector('video'); $video->onloadedmetadata = sub { say( 'The duration and dimensions of the media and tracks are now known.' ); };
Under JavaScript, this is fired when the browser has started to load a resource.
<div class="example"> <button type="button">Load video</button> <video controls width="250"></video> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> use feature 'signatures'; my $loadVideo = $doc->querySelector('button'); my $video = $doc->querySelector('video'); my $eventLog = $doc->querySelector('.event-log-contents'); my $source; sub handleEvent( $event ) { $eventLog->textContent = $eventLog->textContent . $event->type . "\n"; } $video->addEventListener( 'loadstart', \&handleEvent); $video->addEventListener( 'progress', \&handleEvent); $video->addEventListener( 'canplay', \&handleEvent); $video->addEventListener( 'canplaythrough', \&handleEvent); $loadVideo->addEventListener( click => sub { if( $source ) { $doc->location->reload(); } else { $loadVideo->textContent = "Reset example"; $source = $doc->createElement( 'source' ); $source->setAttribute( 'src', 'https://example.org/some/where/media/examples/video.webm' ); $source->setAttribute( 'type', 'video/webm' ); $video->appendChild( $source ); } });
Fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's "pause" in HTML::Object::DOM::Element::Media method is called.
Fired when the paused property is changed from true to false, as a result of the "play" in HTML::Object::DOM::Element::Media method, or the autoplay attribute
use Nice::Try; # for the try{}catch block my $videoElem = $doc->getElementById( 'video' ); my $playButton = $doc->getElementById( 'playbutton' ); $playButton->addEventListener( click => \&handlePlayButton, { capture => 0 }); playVideo(); sub playVideo { try { $videoElem->play(); $playButton->classList->add( 'playing' ); } catch( $err ) { $playButton->classList->remove( 'playing' ); } } sub handlePlayButton { if( $videoElem->paused ) { playVideo(); } else { $videoElem->pause(); $playButton->classList->remove( 'playing' ); } }
Under JavaScript, this is fired when playback is ready to start after having been paused or delayed due to lack of data
my $video = $doc->querySelector('video'); $video->addEventListener( playing =>sub { say( 'Video is no longer paused' ); }); my $video = $doc->querySelector('video'); $video->onplaying = sub { say( 'Video is no longer paused.' ); };
Under JavaScript, this is fired periodically as the browser loads a resource.
<div class="example"> <button type="button">Load video</button> <video controls width="250"></video> <div class="event-log"> <label>Event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> use feature 'signatures'; my $loadVideo = $doc->querySelector('button'); my $video = $doc->querySelector('video'); my $eventLog = $doc->querySelector('.event-log-contents'); my $source; sub handleEvent( $event ) { $eventLog->textContent = $eventLog->textContent . $event->type . "\n"; } $video->addEventListener( 'loadstart', \&handleEvent ); $video->addEventListener( 'progress', \&handleEvent ); $video->addEventListener( 'canplay', \&handleEvent ); $video->addEventListener( 'canplaythrough', \&handleEvent ); $loadVideo->addEventListener( click => sub { if( $source ) { $doc->location->reload(); } else { $loadVideo->textContent = "Reset example"; $source = $doc->createElement('source'); $source->setAttribute( 'src', 'https://example.org/some/where/video.mp4' ); $source->setAttribute( 'type', 'video/mp4' ); $video->appendChild( $source ); } });
This is fired when the playback rate has changed, i.e. when the property "playbackRate" is changed.
my $video = $doc->querySelector( 'video' ); $video->addEventListener( 'ratechange' => sub { say( 'The playback rate changed.' ); }); my $video = $doc->querySelector('video'); $video->onratechange = sub { say( 'The playback rate changed.' ); };
Under JavaScript, this is fired when a seek operation completes
my $video = $doc->querySelector('video'); $video->addEventListener( seeked => sub { say( 'Video found the playback position it was looking for.' ); }); my $video = $doc->querySelector( 'video' ); $video->onseeked = sub { say( 'Video found the playback position it was looking for.' ); };
Under JavaScript, this is fired when a seek operation begins
my $video = $doc->querySelector( 'video' ); $video->addEventListener( seeking => sub { say( 'Video is seeking a new position.' ); }); my $video = $doc->querySelector( 'video' ); $video->onseeking = sub { say( 'Video is seeking a new position.' ); };
Under JavaScript, this is fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
my $video = $doc->querySelector('video'); $video->addEventListener( stalled => sub { say( 'Failed to fetch data, but trying.' ); }); my $video = $doc->querySelector('video'); $video->onstalled = sub { say( 'Failed to fetch data, but trying.' ); };
Under JavaScript, this is fired when the media data loading has been suspended.
my $video = $doc->querySelector('video'); $video->addEventListener( suspend => sub { say( 'Data loading has been suspended.' ); }); my $video = $doc->querySelector( 'video' ); $video->onsuspend = sub { say( 'Data loading has been suspended.' ); };
Fired when the time indicated by the "currentTime" property has been updated.
my $video = $doc->querySelector('video'); $video->addEventListener( timeupdate => sub { say( 'The currentTime attribute has been updated. Again.' ); }); my $video = $doc->querySelector('video'); $video->ontimeupdate = sub { say( 'The currentTime attribute has been updated. Again.' ); };
Fired when the volume has changed, i.e. when the value for the "volume" property has changed.
my $video = $doc->querySelector('video'); $video->addEventListener( volumechange => sub { say( 'The volume changed.' ); }); my $video = $doc->querySelector('video'); $video->onvolumechange = sub { say( 'The volume changed.' ); };
Under JavaScript, this is fired when playback has stopped because of a temporary lack of data.
my $video = $doc->querySelector('video'); $video->addEventListener( waiting => sub { say( 'Video is waiting for more data.' ); }); my $video = $doc->querySelector('video'); $video->onwaiting = sub { say( 'Video is waiting for more data.' ); };
Sets the event handler called when the media is encrypted.
Sets the event handler called when playback is blocked while waiting for an encryption key.
The following constants can be exported and used, such as:
use HTML::Object::DOM::Element::Media qw( :all ); # or directly from HTML::Object::DOM use HTML::Object::DOM qw( :media );
There is no data yet. Also, readyState is HAVE_NOTHING.
Media element is active and has selected a resource, but is not using the network.
The browser is downloading HTML::Object::DOM::Element::Media data.
No HTML::Object::DOM::Element::Media src found.
Jacques Deguest <jack@deguest.jp>
Mozilla documentation, Mozilla documentation on audio element, Mozilla documentation on video element, W3C specifications
Copyright(c) 2021 DEGUEST Pte. Ltd.
All rights reserved
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install HTML::Object, copy and paste the appropriate command in to your terminal.
cpanm
cpanm HTML::Object
CPAN shell
perl -MCPAN -e shell install HTML::Object
For more information on module installation, please visit the detailed CPAN module installation guide.