<audio>

翻译不完整。 请帮助我们翻译这篇文章!

HTML <audio> 元素用于在文档中嵌入音频内容。 <audio> 元素可以包含一个或多个音频资源, 这些音频资源可以使用 src 属性或者<source> 元素来进行描述:浏览器将会选择最合适的一个来使用。也可以使用 MediaStream 将这个元素用于流式媒体。

上述例子展示了 <audio> 元素的基本用法。与 <img> 元素类似,我们在 src 属性中添加了嵌入媒体的路径;也可以使用其他属性来规定一些功能,例如是否自动播放、是否循环播放、是否显示浏览器的默认音频空间等等。

在浏览器不支持该元素时,会显示 <audio></audio> 标签之间的内容作为回退。

属性

该元素包含 全局属性

autoplay
布尔值属性;声明该属性,音频会尽快自动播放,不会等待整个音频文件下载完成。

注意:自动播放音频(或有声视频)可能会破坏用户体验,所以应该尽可能避免。如果你一定要提供自动播放功能,你应该加入开关(让用户主动打开自动播放)。然而,如果需要创建一些媒体元素,其播放源由用户在稍后设置,自动播放就会很有用。想了解如果正确使用自动播放,可参见我们的自动播放指南

controls
如果声明了该属性,浏览器将提供一个包含声音,播放进度,播放暂停的控制面板,让用户可以控制音频的播放。
crossorigin
枚举属性  展示音频资源是否可以通过CROS加载。支持CROS的资源  可以被 <canvas> 元素复用而不污染. 可选值如下:
anonymous
Sends a cross-origin request without a credential. In other words, it sends the Origin: HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted, and its usage restricted.
use-credentials
Sends a cross-origin request with a credential. In other words, it sends the Origin: HTTP header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through Access-Control-Allow-Credentials: HTTP header), the image will be tainted and its usage restricted.
When not present, the resource is fetched without a CORS request (i.e. without sending the Origin: HTTP header), preventing its non-tainted used in <canvas> elements. If invalid, it is handled as if the enumerated keyword anonymous was used. See CORS settings attributes for additional information.
currentTime

Reading currentTime returns a double-precision floating-point value indicating the current playback position, in seconds, of the audio. If the audio's metadata isn't available yet—thereby preventing you from knowing the media's start time or duration—currentTime instead indicates, and can be used to change, the time at which playback will begin. Otherwise, setting currentTime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded.

If the audio is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. Other audio may have a media timeline that doesn't start at 0 seconds, so setting currentTime to a time before that would fail. For example, if the audio's media timeline starts at 12 hours, setting currentTime to 3600 would be an attempt to set the current playback position well before the beginning of the media, and would fail. The getStartDate() method can be used to determine the beginning point of the media timeline's reference frame.

disableRemotePlayback
A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc). See this proposed specification for more information.

In Safari, you can use x-webkit-airplay="deny" as a fallback.

duration 只读
A double-precision floating-point value which indicates the duration (total length) of the audio in seconds, on the media's timeline. If no media is present on the element, or the media is not valid, the returned value is NaN. If the media has no known end (such as for live streams of unknown duration, web radio, media incoming from WebRTC, and so forth), this value is +Infinity.
loop
布尔属性;如果声明该属性,将循环播放音频。
muted
表示是否静音的布尔值。默认值为 false,表示有声音。
preload
枚举属性,让开发者自行思考来示意浏览器使用何种加载方式以达到最好的用户体验。可以是以下属性之一:
  • none: 示意用户可能不会播放该音频,或者服务器希望节省带宽;换句话说,该音频不会被缓存;
  • metadata: 示意即使用户可能不会播放该音频,但获取元数据 (例如音频长度) 还是有必要的。
  • auto: 示意用户可能会播放音频;换句话说,如果有必要,整个音频都将被加载,即使用户不期望使用。
  • 空字符串 : 等效于auto属性。

不同浏览器会有自己的默认值,规范建议的默认值为 metadata.

使用说明:

  • The autoplay attribute has precedence over preload. If autoplay is specified, the browser would obviously need to start downloading the audio for playback.
  • The browser is not forced by the specification to follow the value of this attribute; it is a mere hint
src
嵌入的音频的URL。 该URL应遵从 HTTP access controls. 这是一个可选属性;你可以在audio元素中使用 <source> 元素来替代该属性指定嵌入的音频。

事件

事件名称 触发条件
audioprocess The input buffer of a ScriptProcessorNode is ready to be processed.
canplay The browser 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.
canplaythrough The browser estimates it can play the media up to its end without stopping for content buffering.
complete The rendering of an OfflineAudioContext is terminated.
durationchange The duration attribute has been updated.
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.
ended Playback has stopped because the end of the media was reached.
loadeddata The first frame of the media has finished loading.
loadedmetadata The metadata has been loaded.
pause Playback has been paused.
play Playback has begun.
playing Playback is ready to start after having been paused or delayed due to lack of data.
ratechange The playback rate has changed.
seeked seek operation completed.
seeking seek operation began.
stalled The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
suspend Media data loading has been suspended.
timeupdate The time indicated by the currentTime attribute has been updated.
volumechange The volume has changed.
waiting Playback has stopped because of a temporary lack of data

使用说明

浏览器对 文件类型 和 音频编码 的支持各有不同,你可以使用内嵌的 <source> 元素提供不同的播放源。浏览器会使用第一个它支持的播放源:

<audio controls>
  <source src="myAudio.mp3" type="audio/mpeg">
  <source src="myAudio.ogg" type="audio/ogg">
  <p>Your browser doesn't support HTML5 audio. Here is
     a <a href="myAudio.mp4">link to the audio</a> instead.</p>
</audio>

我们提供了全面细致的 音频文件类型指南 和 这些类型可以使用的音频编码。此外,还有 视频编码支持指南

其他使用说明:

  • 如果你没有声明 controls 属性,音频播放器不会包含浏览器的默认控件。但你可以使用 JavaScript 和 HTMLMediaElement API 创建自己的自定义控件。
  • 为了更精确地控制你的音频内容,HTMLMediaElement 会触发多种不同的 事件。这也提供了一个查看音频获取过程的方式,你可以查看错误或检测什么时候可以开始播放或操作。
  • 你还可以使用 Web Audio API 以从 JavaScript 代码直接生成和操纵音频流,而非流式播放已存在的音频文件。
  • <audio> 元素不能像 <video> 元素一样附加副标题(subtitle)或说明标题(caption)。更多有用的信息和解决方法参见 Ian Devlin 的 WebVTT and Audio

视频和音频内容 新手教程是一篇关于使用 HTML <audio> 的好文章。

使用 CSS 设置样式

<audio> 元素没有自带的固有视觉样式,除非如果声明了 controls 属性,则会显示浏览器的默认控件。

默认控件的 display 的默认值为 inline。将该值设为 block 通常会对定位和布局有好处,除非你想将控件放在文本块或类似元素中。

你可以使用作用于整个控件的属性来为其设置样式。例如可用 borderborder-radiuspadding, margin 等等。但你不能设置音频播放器中的单个组件(如改变按钮大小、改变图标或字体等)。控件在不同的浏览器中也有所不同。

如果在跨浏览器中得到一致的外观和体验,你需要创建自定义控件;自定义控件可以根据你的需求任意设置样式,还可以使用 JavaScript 和 HTMLMediaElement API 来设置更多功能。

视频播放器样式基础 提供了一些有用的样式技术,这篇文章围绕 <video> 而写,但大部分都可以用于 <audio>

检测音轨添加和移除

You can detect when tracks are added to and removed from an <audio> element using the addtrack and removetrack events. However, these events aren't sent directly to the <audio> element itself. Instead, they're sent to the track list object within the <audio> element's HTMLMediaElement that corresponds to the type of track that was added to the element:

HTMLMediaElement.audioTracks
An AudioTrackList containing all of the media element's audio tracks. You can add a listener for addtrack to this object to be alerted when new audio tracks are added to the element.
HTMLMediaElement.videoTracks
Add an addtrack listener to this VideoTrackList object to be informed when video tracks are added to the element.
HTMLMediaElement.textTracks
Add an addtrack event listener to this TextTrackList to be notified when new text tracks are added to the element.

Note: Even though it's an <audio> element, it still has video and text track lists, and can in fact be used to present video, although the use interface implications can be odd.

For example, to detect when audio tracks are added to or removed from an <audio> element, you can use code like this:

var elem = document.querySelector("audio");

elem.audioTrackList.onaddtrack = function(event) {
  trackEditor.addTrack(event.track);
};

elem.audioTrackList.onremovetrack = function(event) {
  trackEditor.removeTrack(event.track);
};

This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks.

You can also use addEventListener() to listen for the addtrack and removetrack events.

示例

基本用法

The following example shows simple usage of the <audio> element to play an OGG file. It will autoplay due to the autoplay attribute—if the page has permission to do so—and also includes fallback content.

<!-- Simple audio playback -->
<audio
  src="AudioTest.ogg"
  autoplay>
  Your browser does not support the <code>audio</code> element.
</audio>

For details on when autoplay works, how to get permission to use autoplay, and how and when it's appropriate to use autoplay, see our autoplay guide.

<audio> 元素与 <source> 元素

This example specifies which audio track to embed using the src attribute on a nested <source> element rather than directly on the <audio> element. It is always useful to include the file's MIME type inside the type attribute, as the browser is able to instantly tell if it can play that file, and not waste time on it if not.

<audio controls>
  <source src="foo.wav" type="audio/wav">
  Your browser does not support the <code>audio</code> element. 
</audio>

<audio> 与多个 <source> 元素

This example includes multiple <source> elements. The browser tries to load the first source element (Opus) if it is able to play it; if not it falls back to the second (Vorbis) and finally back to MP3:

<audio controls>
 <source src="foo.opus" type="audio/ogg; codecs=opus"/>
 <source src="foo.ogg" type="audio/ogg; codecs=vorbis"/>
 <source src="foo.mp3" type="audio/mpeg"/>
</audio>

可访问性考虑

Audio with spoken dialog should provide both captions and transcripts that accurately describe its content. Captions, which are specified using WebVTT, allow people who are experiencing hearing loss to understand an audio recording's content as the recording is being played, while transcripts allow people who need additional time to be able to review the recording's content at a pace and format that is comfortable for them.

If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source audio.

The <audio> element doesn't directly support WebVTT. You will have to find a library or framework that provides the capability for you, or write the code to display captions yourself. One option is to play your audio using a <video> element, which does support WebVTT.

In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth.

1
00:00:00 --> 00:00:45
[Energetic techno music]

2 
00:00:46 --> 00:00:51
Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch?

16
00:00:52 --> 00:01:02
[Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch?

Also it's a good practice to provide some content (such as the direct download link) as a fallback for viewers who use a browser in which the <audio> element is not supported:

<audio controls>
  <source src="myAudio.mp3" type="audio/mpeg">
  <source src="myAudio.ogg" type="audio/ogg">
  <p>
    Your browser doesn't support HTML5 audio.
    Here is a <a href="myAudio.mp4">link to download the audio</a> instead.
  </p>
</audio>

技术概览

Content categories Flow content, phrasing content, embedded content. If it has a controls attribute: interactive content and palpable content.
Permitted content If the element has a src attribute: zero or more <track> elements followed by transparent content that contains no <audio> or <video> media elements.
Else: zero or more <source> elements followed by zero or more <track> elements followed by transparent content that contains no <audio> or <video> media elements.
Tag omission 不允许,开始标签和结束标签都不能省略。
Permitted parents Any element that accepts embedded content.
Implicit ARIA role No corresponding role
Permitted ARIA roles application
DOM interface HTMLAudioElement

规范

Specification Status Comment
HTML Living Standard
<audio>
Living Standard
HTML5
<audio>
Recommendation

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
audioChrome Full support 3Edge Full support 12Firefox Full support 3.5
Notes
Full support 3.5
Notes
Notes For Firefox to play audio, the server must serve the file using the correct MIME type.
IE Full support 9Opera Full support 10.5Safari Full support 3.1WebView Android Full support 3Chrome Android Full support 18Firefox Android Full support 4
Notes
Full support 4
Notes
Notes For Firefox to play audio, the server must serve the file using the correct MIME type.
Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0
autoplayChrome Full support 3Edge Full support 12Firefox Full support 3.5IE Full support 9Opera Full support 10.5Safari Full support 3.1WebView Android Full support 3Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0
bufferedChrome ? Edge Full support ≤18Firefox Full support 4IE ? Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android Full support 4Opera Android ? Safari iOS ? Samsung Internet Android ?
controlsChrome Full support 3Edge Full support 12Firefox Full support 3.5IE Full support 9Opera Full support 10.5Safari Full support 3.1WebView Android Full support 3Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0
loopChrome Full support 3Edge Full support 12Firefox Full support 11IE Full support 9Opera Full support 10.5Safari Full support 3.1WebView Android Full support 3Chrome Android Full support 18Firefox Android Full support 14Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0
mozcurrentsampleoffset
Non-standard
Chrome No support NoEdge No support NoFirefox Full support 3.5IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox Android Full support 4Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support No
mutedChrome ? Edge Full support ≤18Firefox Full support 11IE ? Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android Full support 14Opera Android ? Safari iOS ? Samsung Internet Android ?
playedChrome Full support 49Edge Full support 14Firefox Full support 15IE Full support 11Opera Full support 46Safari Full support 9.1WebView Android Full support 49Chrome Android Full support 49Firefox Android Full support 15Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 5.0
preloadChrome Full support 3
Notes
Full support 3
Notes
Notes Defaults to metadata in Chrome 64.
Edge Full support 12Firefox Full support 4
Full support 4
No support 3.5 — 4
Alternate Name
Alternate Name Uses the non-standard name: autobuffer
IE Full support 9Opera Full support 15
Notes
Full support 15
Notes
Notes Defaults to metadata in Opera 51.
No support 10.5 — 15
Alternate Name
Alternate Name Uses the non-standard name: autobuffer
Safari Full support 3.1WebView Android Full support 3
Notes
Full support 3
Notes
Notes Defaults to metadata in Chrome 64.
Chrome Android Full support 18
Notes
Full support 18
Notes
Notes Defaults to metadata in Chrome 64.
Firefox Android Full support 4Opera Android Full support 14
Notes
Full support 14
Notes
Notes Defaults to metadata in Opera 51.
No support ? — 14
Alternate Name
Alternate Name Uses the non-standard name: autobuffer
Safari iOS Full support YesSamsung Internet Android Full support 1.0
Notes
Full support 1.0
Notes
Notes Defaults to metadata in Samsung Internet 9.0.
srcChrome Full support 3Edge Full support 12Firefox Full support 3.5IE Full support 9Opera Full support 10.5Safari Full support 3.1WebView Android Full support 3Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support 1.0
volumeChrome ? Edge Full support ≤18Firefox ? IE ? Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android ? Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
See implementation notes.
See implementation notes.
Uses a non-standard name.
Uses a non-standard name.

参见