一款兼容性较强的H5播放器-Mediaelementjs

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处: http://www.cnblogs.com/mao2080/

Attributes

MediaElement supports the following video/audio tag attributes:

AttributeDescription
autoplaySpecifies that the video will start playing as soon as it is ready
classSpecifies one or more class names for an element (refers to a class in a style sheet)
controlsSpecifies that video controls should be displayed (such as a play/pause button etc).
idSpecifies a unique id for an element; if not specified, the plugin will create one automatically
heightSets the height of the video player in pixels; you can also indicate percentages
loopSpecifies that the video will start over again, every time it is finished
mutedSpecifies that the audio output of the video should be muted
posterSpecifies an image to be shown while the video is downloading, or until the user hits the play button. Generally, a PNG or JPEG image. If not specified, the player will use the background color specified in the style sheet
preloadSpecifies if and how the author thinks the video should be loaded when the page loads; possible values: auto, metadata or none (recommended)
srcSpecifies the URL of the video file; this value can also be indicated with source tags (refer to the Multiple Codecs section for more information)
styleSpecifies an inline CSS style for an element
tabindexSpecifies the tabbing order of an element. To avoid the keyboard to focus on this element, use -1; otherwise, 0
titleSpecifies extra information about an element
widthSets the width of the video player in pixels; you can also indicate percentages

The following markup displays all the attributes listed above for more clarity:

<video autoplay controls class="player" id="player1" height="360"
	width="100%" loop muted poster="/path/to/poster.jpg"
	preload="none" src="/path/to/media.mp4"
	style="max-width: 100%" tabindex="0" title="MediaElement">
</video>

 

Configuration

 

Standalone

As a standalone library, MediaElement.js can be configured using the following settings.

ParameterTypeDefaultDescription
renderersarray[]List of the renderers to use
fakeNodeNamestringmediaelementwrapperName of MediaElement container
pluginPathstringbuild/Path where Flash shims are located
shimScriptAccessstringsameDomainFlag in <object> and <embed> to determine whether to use local or CDN files. Possible values: always (CDN version) or sameDomain (local files)
successcallback Action(s) that will be executed as soon as the source is loaded; passes 2 arguments: media (the wrapper that mimics all the native events/properties/methods for all renderers) and node (the original HTML video, audio or iframe tag where the media was loaded originally; if html5 is being used, media and node are the basically the same)
errorcallback Action(s) that will be executed if source doesn't load for any reason. Passes same arguments as success
dailymotionobject See Documentation
dashobject Accepts debug, drm (object to load protected/licensed streaming; read here for more information) and path parameters to indicate dash.js URL/local path
facebookobject See Documentation (and a custom lang parameter to indicate the FB SDK language)
flvobject See Documentation (and a custom path parameter to indicate where to load library)
hlsobject See Documentation (and a custom path parameter to indicate where to load library)
youtubeobject See Documentation; also, a custom nocookie parameter to switch to YouTube's no-cookie URL and imageQuality parameter if user decides to use Image API to load a YouTube poster based on YouTube video ID (possible values: default, hqdefault, mqdefault, sddefault and maxresdefault)

Notes

  1. Vimeo and Soundcloud don't need any configuration for now since they are pretty straight forward.
  2. To use DRM with M(PEG)-DASH, make sure CORS are configured correctly, and also your site MUST be using SSL.
  3. Both success and error will be available for both MediaElement and MediaElementPlayer; however, when using MediaElementPlayer, a third argument is passed: instance, which gives access to the methods associated to the MediaElementPlayer class.
  4. When using MediaElementPlayer, error arguments will be: error (the details on the error event), media and node.

 

MediaElementPlayer

Including the above, MediaElementPlayer object allows the following extra configuration elements.

ParameterTypeDefaultDescription
classPrefixstringmejs__Class prefix for player elements
posterstring(empty)Poster URL that overrides poster attribute
showPosterWhenEndedbooleanfalseWhen the video is ended, show the poster
showPosterWhenPausedbooleanfalseWhen the video is paused, show the poster
defaultVideoWidthnumber480Default width if the <video> width is not specified
defaultVideoHeightnumber270Default height if the <video> height is not specified
videoWidthnumber-1If set, overrides <video> width
videoHeightnumber-1If set, overrides <video> height
defaultAudioWidthnumber400Default width for audio player if the user doesn't specify
defaultAudioHeightnumber30Default height for audio player if the user doesn't specify
defaultSeekBackwardIntervalfunction Default amount to move back when back key is pressed. Default callback is represented like: function(media) {return (media.duration * 0.05);}
defaultSeekForwardIntervalfunction Default amount to move forward when forward key is pressed. Default callback is represented like: function(media) {return (media.duration * 0.05);}
setDimensionsbooleantrueSet dimensions via JS instead of CSS
audioWidthnumber-1Width of audio player
audioHeightnumber-1Height of audio player
startVolumenumber0.8Initial volume when the player starts (overrided by user cookie); represented with float values
loopbooleanfalseWhether to loop or not media
autoRewindbooleantrueRewind to beginning when media ends
enableAutosizebooleantrueResize to media dimensions
timeFormatstring(empty)Time format to use. Default: 'mm:ss'. Supported units: h: hour, m: minute, s: second and f: frame count. If use 2 letters, 2 digits will be displayed (hh:mm:ss)
alwaysShowHoursbooleanfalseForce the hour marker (##:00:00)
showTimecodeFrameCountbooleanfalseWhether to show frame count in timecode (##:00:00:00)
framesPerSecondnumber25Used when showTimecodeFrameCount is set to true
autosizeProgressbooleantrueAutomatically calculate the width of the progress bar based on the sizes of other elements
alwaysShowControlsbooleanfalseHide controls when playing and mouse is not over the video
hideVideoControlsOnLoadbooleanfalseDisplay the video control when media is loading
hideVideoControlsOnPausebooleanfalseDisplay the video controls when media is paused
clickToPlayPausebooleantrueEnable click video element to toggle play/pause
controlsTimeoutDefaultnumber1500Time in ms to hide controls
controlsTimeoutMouseEnternumber2500Time in ms to trigger the timer when mouse moves
controlsTimeoutMouseLeavenumber1000Time in ms to trigger the timer when mouse leaves
iPadUseNativeControlsbooleanfalseForce iPad's native controls
iPhoneUseNativeControlsbooleanfalseForce iPhone's native controls
AndroidUseNativeControlsbooleanfalseForce Android's native controls
featuresarray[...]List of features/plugin to use in the player; some will be included in the control bar (by default IN STRICT ORDER: playpause, current, progress, duration, tracks, volume, fullscreen)
useDefaultControlsbooleanfalseIf set to true, all the default control elements listed in features above will be used, and the features will append any other plugins indicated in features. This approach is used mostly when adding more plugins WITHOUT modifying the elements in the control bar in any capacity
isVideobooleantrueOnly for dynamic purposes
stretchingstringautoStretching modes for video player. If auto is set, player will try to find the max-width and max-height CSS styles to turn it into responsive mode; otherwise, will set the dimensions specified in the tag (same as setting this option as none). The fill mode will try to use the available space to make the video fit and, when window is resized, it will crop the dimensions to center it according to the available space.
enableKeyboardbooleantrueTurns keyboard support on and off for this instance
pauseOtherPlayersbooleantrueWhen focused player starts, it will pause other players
secondsDecimalLengthnumber0Number of decimal places to show if frames are shown
customErrorstring/callbacknullIf error happens, set up customized HTML message through a string or a function. The function has 2 parameters: media (the wrapper that mimics all the native events/properties/methods for all renderers) and node (the original HTML video, audio or iframe tag where the media was loaded originally)
keyActionsarray[...]Keyboard actions to trigger different actions. Accepts array of objects in format: {keys: [1,2,3...], action: function(player, media) { ... }}. To see the entire list, please check /src/js/mediaelementplayer-player.js
durationnumber-1Start point to detect changes on media time duration
timeAndDurationSeparatorstring<span> &#124; </span>Separator between the current time and the total duration of media being played
hideVolumeOnTouchDevicesbooleantrueTouch devices (specially mobile devices) have different way to handle volume, so no need to display it
enableProgressTooltipbooleantrueEnable/disable tooltip that shows time popup in progress bar
useSmoothHoverbooleantrueEnable smooth behavior when hovering progress bar (like YouTube's)
forceLivebooleanfalseIf set to true, the Live Broadcast message will be displayed and progress bar will be hidden, no matter if duration is a valid number
audioVolumestringhorizontalPosition of volume slider on audio element
videoVolumestringverticalPosition of volume slider on video element
usePluginFullScreenbooleantrueFlag to activate detection of Pointer events when on fullscreen mode
useFakeFullscreenbooleanfalseFlag to bypass native capabilities on mobile devices and use the fake-fullscreen mode
tracksAriaLivebooleanfalseBy default, no WAI-ARIA live region - don't make a screen reader speak captions over an audio track.
hideCaptionsButtonWhenEmptybooleantrueOption to remove the [cc] button when no <track kind="subtitles"> are present
toggleCaptionsButtonWhenOnlyOnebooleanfalseIf true and we only have one track, change captions to popup
startLanguagestring(empty)Automatically turn on a <track> element
slidesSelectorstring(empty)Selector for slides; could be any valid Javascript selector (#id, .class, img, etc.)
tracksTextstringnullTitle for Closed Captioning button for WARIA purposes
chaptersTextstringnullTitle for Chapters button for WARIA purposes
muteTextstringnullTitle for Mute button for WARIA purposes
unmuteTextstringnullTitle for Unmute button for WARIA purposes
allyVolumeControlTextstringnullTitle for Volume slider for WARIA purposes
fullscreenTextstringnullTitle for Fullscreen button for WARIA purposes
playTextstringnullTitle for Play/Pause button for WARIA purposes when media is playing
pauseTextstringnullTitle for Play/Pause button for WARIA purposes when media is paused

 

API

MediaElementPlayer is a complete audio and video player, but you can also use just the MediaElement object which replaces <video> and <audio> with a Flash player that mimics the properties, methods, and events of HTML MediaElement API.

 

Properties

PropertyDescriptionGETSET
autoplaySet or return whether the audio/video should start playing as soon as it is loadedXX
bufferedReturn a TimeRanges object representing the buffered parts of the audio/videoX 
controlsSet or return whether the audio/video should display controls (like play/pause etc.)XX
currentSrcReturn the URL of the current audio/videoX 
currentTimeSet or return the current playback position in the audio/video (in seconds)XX
durationReturn the length of the current audio/video (in seconds); to determine it without playing media, preload="auto" must be setX 
endedReturn whether the playback of the audio/video has ended or notX 
errorReturn a MediaError object representing the error state of the audio/videoX 
loopSet or return whether the audio/video should start over again when finishedXX
mutedSet or returns whether the audio/video is muted or notXX
pausedReturn whether the audio/video is paused or notX 
readyStateReturn the current ready state of the audio/videoX 
seekingReturn whether the user is currently seeking in the audio/videoX 
srcSet or return the current source of the audio/video elementXX
volumeSet or return the volume of the audio/videoXX

 

Methods

MethodDescription
load()Reload the audio/video element; also, it is used to update the audio/video element after changing the source or other settings
play()Start playing the audio/video
pause()Halt (pauses) the currently playing audio or video
stop()Only present to support Flash RTMP streaming in MediaElementPlayer. The equivalent for other scenarios is pause
remove()Destroy the video/audio player instance
canPlayType(type)Determine whether current player can/cannot play a specific media type; type is MIME type and each renderer has a whitelist of them
setPlayerSize (width, height)Set player's width and height also considering the stretching configuration
setPoster (url)Add a image tag with the poster's url inside the player's layer; you can pass an empty string to clear the poster
setMuted (muted)Mute/unmute the player; muted is a boolean value
setCurrentTime (time)Set a new current time for the player; time is either an integer or float number, and if negative, it will start from zero.
getCurrentTime ()Retrieve the current time of the media being played
setVolume (volume)Set a volume level for the player; volume is a number between 0 and 1
getVolume ()Retrieve the current volume level of the media being played
setSrc (src)Set a new URL/path for the player; each renderer has a different mechanism to set it
getSrc ()Retrieve the media URL/path currently being played; each renderer has a different mechanism to return it

 

Events

EventAction(s) executed when...
loadedmetadataMeta data (like dimensions and duration) are loaded
progressBrowser is in the process of getting the media data
timeupdateThe playing position has changed (like when the user fast forwards to a different point in the media)
seekingThe seeking attribute is set to true indicating that seeking has started
seekedThe seeking attribute is set to false indicating that seeking has ended
canplayA file is ready to start playing (when it has buffered enough to begin)
playThe media is ready to start playing
playingThe media actually has started playing
pauseThe media is paused either by the user or programmatically
endedThe media has reach the end (a useful event for messages like "thanks for listening")
volumechangeVolume is changed (including setting the volume to "mute")
captionschangeThe media has detected that captions have changed

原文链接:https://github.com/mediaelement/mediaelement/blob/master/docs/api.md#attributes

下载地址:mediaelementjs.rar

转载于:https://www.cnblogs.com/mao2080/p/7667607.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值