乐闻世界logo
搜索文章和话题

WebRTC - How to identify the source IDs (device IDs) for a MediaStream( Tracks )

1个答案

1

In WebRTC, each MediaStream consists of multiple MediaStreamTrack objects, which can represent audio or video tracks. If you need to determine the source device ID of a MediaStreamTrack, you can obtain it using the MediaDeviceInfo object.

First, you need to retrieve a list of all available media input devices on the user's device. This can be done using the navigator.mediaDevices.enumerateDevices() method, which returns an array of MediaDeviceInfo objects containing information about all media devices. Each MediaDeviceInfo object includes properties such as kind, label, and deviceId.

The following steps outline how to retrieve device IDs and associate them with MediaStreamTrack:

  1. Obtain the List of Available Devices: Call navigator.mediaDevices.enumerateDevices(), an asynchronous function that returns a Promise resolving to an array of MediaDeviceInfo objects.

    javascript
    navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices.forEach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceId); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); });
  2. Create or Obtain a MediaStream: When you create or obtain a MediaStream, you can access its getTracks() method, which returns an array of MediaStreamTrack objects.

    javascript
    navigator.mediaDevices.getUserMedia({ audio: true, video: true }) .then(function(stream) { // Retrieve all tracks var tracks = stream.getTracks(); tracks.forEach(function(track) { console.log(track.kind + " track: " + track.label); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); });
  3. Associate MediaStreamTrack with Device ID: Generally, after the user grants access to media devices, the label property of a MediaStreamTrack object matches the label property of a corresponding MediaDeviceInfo object. This allows you to associate the track with a specific device ID.

    javascript
    navigator.mediaDevices.getUserMedia({ video: true }) .then(function(stream) { var videoTrack = stream.getVideoTracks()[0]; navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices.forEach(function(device) { if (device.kind === 'videoinput' && device.label === videoTrack.label) { console.log("Video track device ID: " + device.deviceId); } }); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); });

This process ensures you can identify the source device for each MediaStreamTrack, which is essential for complex audio and video processing scenarios, such as distinguishing between different cameras or microphones.

2024年8月18日 23:16 回复

你的答案