HTMLMediaElement play() method attempts to begin playback of the media. It returns a Promise which is resolved when playback has been successfully started. Failure to begin playback for any reason, such as permission issues, result in the promise being rejected.

句法

var promise = HTMLMediaElement.play();
					

参数

None.

返回值

A Promise which is resolved when playback has been started, or is rejected if for any reason playback cannot be started.

注意: Older browsers may not return a value from play() .

异常

The promise's rejection handler is called with an exception name passed in as its sole input parameter (as opposed to a traditional exception being thrown). Possible errors include:

NotAllowedError

The user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button.

NotSupportedError
The media source (which may be specified as a MediaStream , MediaSource , Blob ,或 File , for example) doesn't represent a supported media format.

Other exceptions may be reported, depending on browser implementation details, media player implementation, and so forth.

用法注意事项

Although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to play() .

用户代理 is configured not to allow automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a NotAllowedError . Web sites should be prepared to handle this situation. For example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their UI based on whether the returned promise is resolved or rejected. See the 范例 below for more information.

注意: play() method may cause the user to be asked to grant permission to play the media, resulting in a possible delay before the returned promise is resolved. Be sure your code doesn't expect an immediate response.

For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs .

范例

This example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback:

let videoElem = document.getElementById("video");
let playButton = document.getElementById("playbutton");
playButton.addEventListener("click", handlePlayButton, false);
playVideo();
async function playVideo() {
  try {
    await videoElem.play();
    playButton.classList.add("playing");
  } catch(err) {
    playButton.classList.remove("playing");
  }
}
function handlePlayButton() {
  if (videoElem.paused) {
    playVideo();
  } else {
    videoElem.pause();
    playButton.classList.remove("playing");
  }
}
					

In this example, playback of video is toggled off and on by the async playVideo() function. It tries to play the video, and if successful sets the class name of the playButton element to "playing" . If playback fails to start, the playButton element's class is cleared, restoring its default appearance. This ensures that the play button matches the actual state of playback by watching for the resolution or rejection of the Promise 返回通过 play() .

When this example is executed, it begins by collecting references to the <video> element as well as the <button> used to toggle playback on and off. It then sets up an event handler for the click event on the play toggle button and attempts to automatically begin playback by calling playVideo() .

You can try out or remix this example in real time on Glitch .

规范

规范 状态 注释
HTML 实时标准
The definition of 'play()' in that specification.
实时标准 Initial definition; living specification.
HTML5
The definition of 'play()' in that specification.
推荐 初始定义。

注意: The WHATWG and W3C versions of the specification differ (as of August, 2018) as to whether this method returns a Promise or nothing at all, respectively.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
play Chrome 1 Edge 12 Firefox 3.5 IE 9 Opera 10.5 Safari 6 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 11 Safari iOS 6 Samsung Internet Android 1.0
返回 Promise Chrome 50 Edge 17 Firefox 53 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 53 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改:
  1. HTMLMediaElement
  2. 特性
    1. audioTracks
    2. autoplay
    3. buffered
    4. controller
    5. controls
    6. controlsList
    7. crossOrigin
    8. currentSrc
    9. currentTime
    10. defaultMuted
    11. defaultPlaybackRate
    12. duration
    13. ended
    14. error
    15. initialTime
    16. loop
    17. mediaGroup
    18. muted
    19. networkState
    20. onerror
    21. paused
    22. playbackRate
    23. readyState
    24. seekable
    25. sinkId
    26. src
    27. srcObject
    28. textTracks
    29. videoTracks
    30. volume
  3. 方法
    1. canPlayType()
    2. captureStream()
    3. fastSeek()
    4. load()
    5. msInsertAudioEffect()
    6. pause()
    7. play()
    8. seekToNextFrame()
    9. setMediaKeys()
    10. setSinkId()
  4. 事件
    1. abort
    2. canplay
    3. canplaythrough
    4. durationchange
    5. emptied
    6. ended
    7. error
    8. loadeddata
    9. loadedmetadata
    10. loadstart
    11. pause
    12. play
    13. progress
    14. ratechange
    15. seeked
    16. seeking
    17. stalled
    18. suspend
    19. timeupdate
    20. volumechange
    21. waiting
  5. 继承:
    1. HTMLElement
    2. 元素
    3. 节点
    4. EventTarget
  6. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. GlobalEventHandlers
    5. HTMLAnchorElement
    6. HTMLAreaElement
    7. HTMLAudioElement
    8. HTMLBRElement
    9. HTMLBaseElement
    10. HTMLBaseFontElement
    11. HTMLBodyElement
    12. HTMLButtonElement
    13. HTMLCanvasElement
    14. HTMLContentElement
    15. HTMLDListElement
    16. HTMLDataElement
    17. HTMLDataListElement
    18. HTMLDialogElement
    19. HTMLDivElement
    20. HTMLDocument
    21. HTMLElement
    22. HTMLEmbedElement
    23. HTMLFieldSetElement
    24. HTMLFormControlsCollection
    25. HTMLFormElement
    26. HTMLFrameSetElement
    27. HTMLHRElement
    28. HTMLHeadElement
    29. HTMLHeadingElement
    30. HTMLHtmlElement
    31. HTMLIFrameElement
    32. HTMLImageElement
    33. HTMLInputElement
    34. HTMLIsIndexElement
    35. HTMLKeygenElement
    36. HTMLLIElement
    37. HTMLLabelElement
    38. HTMLLegendElement
    39. HTMLLinkElement
    40. HTMLMapElement
    41. HTMLMetaElement
    42. HTMLMeterElement
    43. HTMLModElement
    44. HTMLOListElement
    45. HTMLObjectElement
    46. HTMLOptGroupElement
    47. HTMLOptionElement
    48. HTMLOptionsCollection
    49. HTMLOutputElement
    50. HTMLParagraphElement
    51. HTMLParamElement
    52. HTMLPictureElement
    53. HTMLPreElement
    54. HTMLProgressElement
    55. HTMLQuoteElement
    56. HTMLScriptElement
    57. HTMLSelectElement
    58. HTMLShadowElement
    59. HTMLSourceElement
    60. HTMLSpanElement
    61. HTMLStyleElement
    62. HTMLTableCaptionElement
    63. HTMLTableCellElement
    64. HTMLTableColElement
    65. HTMLTableDataCellElement
    66. HTMLTableElement
    67. HTMLTableHeaderCellElement
    68. HTMLTableRowElement
    69. HTMLTableSectionElement
    70. HTMLTemplateElement
    71. HTMLTextAreaElement
    72. HTMLTimeElement
    73. HTMLTitleElement
    74. HTMLTrackElement
    75. HTMLUListElement
    76. HTMLUnknownElement
    77. HTMLVideoElement
    78. HashChangeEvent
    79. 历史
    80. ImageData
    81. 定位
    82. MessageChannel
    83. MessageEvent
    84. MessagePort
    85. Navigator
    86. NavigatorGeolocation
    87. NavigatorID
    88. NavigatorLanguage
    89. NavigatorOnLine
    90. NavigatorPlugins
    91. PageTransitionEvent
    92. Plugin
    93. PluginArray
    94. PopStateEvent
    95. PortCollection
    96. PromiseRejectionEvent
    97. RadioNodeList
    98. Transferable
    99. ValidityState
    100. Window
    101. WindowBase64
    102. WindowEventHandlers
    103. WindowTimers