This document defines a set of JavaScript APIs that let a Web application manage how audio is rendered on the user audio output devices.

The WebRTC and Device and Sensors Working Group intend to publish this specification as a Candidate Recommendation soon. Consequently, this is a Request for wide review of this document.

Introduction

This proposal allows JavaScript to direct the audio output of a media element to permitted devices other than the system or user agent default. This can be helpful in a variety of real-time communication scenarios as well as general media applications. For example, an application can use this API to programmatically direct output to a device such as a Bluetooth headset or speakerphone.

{{HTMLMediaElement}} Extensions

This section specifies additions to the {{HTMLMediaElement}} [[HTML]] when the Audio Output Devices API is supported.

When the {{HTMLMediaElement}} constructor is invoked, the user agent MUST add the following initializing step:

  1. Let the element have a [[\SinkId]] internal slot, initialized to "".

      partial interface HTMLMediaElement {
        [SecureContext] readonly attribute DOMString sinkId;
        [SecureContext] Promise<undefined> setSinkId (DOMString sinkId);
      };
      

Attributes

sinkId of type {{DOMString}}, readonly

This attribute contains the ID of the audio device through which output is being delivered, or the empty string if output is delivered through the user-agent default device. If nonempty, this ID should be equal to the {{MediaDeviceInfo/deviceId}} attribute of one of the {{MediaDeviceInfo}} values returned from {{MediaDevices/enumerateDevices()}}.

On getting, the attribute MUST return the value of the {{HTMLMediaElement/[[SinkId]]}} slot.

Methods

setSinkId

Sets the ID of the audio device through which audio output should be rendered if the application is permitted to play out of a given device.

When this method is invoked, the user agent must run the following steps:

  1. Let document be the current settings object's responsible document.

  2. If document is not allowed to use the feature identified by "speaker-selection", return a promise rejected with a new {{DOMException}} whose name is {{NotAllowedError}}.

  3. Let element be the {{HTMLMediaElement}} object on which this method was invoked.

  4. Let sinkId be the method's first argument.

  5. If sinkId is equal to element's {{HTMLMediaElement/[[SinkId]]}}, return a promise resolved with undefined.

  6. Let p be a new promise.

  7. Run the following substeps in parallel:

    1. If sinkId is not the empty string and does not match any audio output device identified by the result that would be provided by {{MediaDevices/enumerateDevices()}}, reject p with a new {{DOMException}} whose name is {{NotFoundError}} and abort these substeps.

    2. If sinkId is not the empty string, and the application would not be permitted to play audio through the device identified by sinkId if it weren't the current user agent default device, reject p with a new {{DOMException}} whose name is {{NotAllowedError}} and abort these substeps.

    3. Switch the underlying audio output device for element to the audio device identified by sinkId.

      If this substep is successful and the media element's {{HTMLMediaElement/paused}} attribute is false, audio MUST stop playing out of the device represented by the element's {{HTMLMediaElement/sinkId}} attribute and will start playing out of the device identified by sinkId

    4. If the preceding substep failed, reject p with a new {{DOMException}} whose name is {{AbortError}}, and abort these substeps.

    5. Queue a task that runs the following steps:

      1. Set element's {{HTMLMediaElement/[[SinkId]]}} to sinkId.

      2. Resolve p.

  8. Return p.

Algorithms

Sink no longer available

The audio device identified by a media element's {{HTMLMediaElement/sinkId}} attribute may become unavailable, for example if it is unplugged.

When the audio device identified by the {{HTMLMediaElement/sinkId}} attribute is no longer available, the user agent must take no action. For example, if the media element's {{HTMLMediaElement/paused}} attribute is false when the device identified by the sinkId is no longer available, then playback will continue as normal. In this case, audio will not be rendered because the device to which the media element is attached is unavailable.

The following paragraph is non-normative.

If the application wishes to react to the device change, the application can listen to the devicechange event and query {{MediaDevices/enumerateDevices()}} for the list of updated devices. If the value of the media element's {{HTMLMediaElement/sinkId}} attribute is no longer present as the {{MediaDeviceInfo/deviceId}} attribute in the returned list of {{MediaDeviceInfo}}s, the device is no longer available and the application can choose to react accordingly.

New sink available

New audio devices may become available to the user agent, or an audio device (identified by a media element's {{HTMLMediaElement/sinkId}} attribute) that had previously become [= unavailable =] may become available again, for example, if it is unplugged and later plugged back in.

In this scenario, the user agent must run the following steps:

  1. Let sinkId be the identifier for the newly available device.

  2. For each media element whose {{HTMLMediaElement/sinkId}} attribute is equal to sinkId:

    1. If the media element's {{HTMLMediaElement/paused}} attribute is false, start rendering this object's audio out of the device represented by the {{HTMLMediaElement/sinkId}} attribute.

The following paragraph is non-normative.

If the application wishes to react to the device change, the application can listen to the devicechange event and query {{MediaDevices/enumerateDevices()}} for the list of updated devices.

{{MediaDevices}} Extensions

This section specifies additions to the {{MediaDevices}} when the Audio Output Devices API is supported.

      partial interface MediaDevices {
        Promise<MediaDeviceInfo> selectAudioOutput(optional AudioOutputOptions options = {});
      };
      

Methods

selectAudioOutput

Prompts the user to select a specific audio output device.

When the {{selectAudioOutput}} method is called, the User Agent MUST run the following steps:

  1. If the [=relevant global object=] of [=this=] does not have [=transient activation=], return a promise rejected with a {{DOMException}} object whose {{DOMException/name}} attribute has the value {{InvalidStateError}}.

  2. Let options be the method's first argument.

  3. Let deviceId be options.deviceId.

  4. Let p be a new promise.

  5. Run the following steps in parallel:

    1. Let descriptor be a {{PermissionDescriptor}} named {{PermissionName/"speaker-selection"}}.

    2. If descriptor's [=permission state=] is {{PermissionState/"denied"}}, reject p with a new {{DOMException}} whose {{DOMException/name}} attribute has the value {{NotAllowedError}}, and abort these steps.

    3. Probe the User Agent for available audio output devices.

    4. If there is no audio output device, reject p with a new {{DOMException}} whose {{DOMException/name}} attribute has the value {{NotFoundError}} and abort these steps.

    5. If deviceId is not "" and matches an id previously exposed by {{MediaDevices/selectAudioOutput}} in an earlier browsing session, the user agent MAY decide, based on its previous decision of whether to persist this id or not for this set of origins, to run the following sub steps:

      1. Let device be the device identified by deviceId, if available.

      2. If device is available, resolve p with either deviceId or a freshly rotated device id for device, and abort the in-parallel steps.

    6. [=Prompt the user to choose=] an audio output device, with descriptor.

    7. If the result of the request is {{PermissionState/"denied"}}, reject p with a new {{DOMException}} whose {{DOMException/name}} attribute has the value {{NotAllowedError}} and abort these steps.

    8. Let deviceInfo be a new {{MediaDeviceInfo}} object to represent the selected audio output device.

    9. Add deviceInfo.{{MediaDeviceInfo/deviceId}} to [[\explicitlyGrantedAudioOutputDevices]].

    10. Resolve p with deviceInfo.

  6. Return p.

Once a device is exposed after a call to {{MediaDevices/selectAudioOutput}}, it MUST be listed by {{MediaDevices/enumerateDevices()}} for the current browsing context.

If the promise returned by {{MediaDevices/selectAudioOutput}} is resolved, then the user agent MUST ensure the document is both immediately allowed to play media in an {{HTMLMediaElement}}, and immediately allowed to start an {{AudioContext}}, without needing any additional user gesture.

This is imprecise due to the current lack of standardization of autoplay in browsers.

AudioOutputOptions dictionary

This dictionary describes the options that can be used to obtain access to an audio output device.

dictionary AudioOutputOptions {
  DOMString deviceId = "";
};

Dictionary AudioOutputOptions Members

deviceId of type {{DOMString}}, defaulting to ""

When the value of this dictionary member is not "", and matches the id previously exposed by {{MediaDevices/selectAudioOutput}} in an earlier session, the user agent MAY opt to skip prompting the user in favor of resolving with this id or a new rotated id for the same device, assuming that device is currently available.

Applications that wish to rely on user agents supporting persisted device ids must pass these through {{MediaDevices/selectAudioOutput}} successfully before they will work with {{HTMLMediaElement/setSinkId}}. The reason for this is that it exposes fingerprinting information, but at the risk of prompting the user if the device is not available or the user agent decides not to honor the device id.

Privacy Considerations

Permissions Policy Integration

This specification defines one [=policy-controlled feature=] identified by the string "speaker-selection". It has a [=default allowlist=] of "self".

A [=document=]'s [=Document/permissions policy=] determines whether any content in that document is [=allowed to use=] {{MediaDevices/selectAudioOutput}} to prompt the user for an audio output device, or [=allowed to use=] {{HTMLMediaElement/setSinkId}} to change the device through which audio output should be rendered, to a non-system-default user-permitted device. For {{MediaDevices/selectAudioOutput}} this is enforced by the [=prompt the user to choose=] algorithm.

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)

Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [[!WEBIDL]], as this specification uses that specification and terminology.

Acknowledgments

The following people have contributed directly to the development of this specification: Harald Alvestrand, Rick Byers, Dominique Hazael-Massieux (via the HTML5Apps project), Philip Jägenstedt, Victoria Kirst, Shijun Sun, Martin Thomson, Chris Wilson.