<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Audio Output Devices API</title>
</head>
<body>
<strong>Audio Output Devices API</strong>
<hr />
<button type="button" class="btn-select">play</button>
<script>
// Audio Output Devices API
// 音频输出设备API允许Web应用程序提示用户应使用什么输出设备进行音频播放。
const selectBtn = document.querySelector('.btn-select');
const audio = new Audio('./tts.mp3');
let played = false;
selectBtn.addEventListener('click', async () => {
if (played) {
audio.paused ? audio.play() : audio.pause();
selectBtn.textContent = !audio.paused ? 'pause' : 'play';
return;
}
const audioDevice = await navigator.mediaDevices.selectAudioOutput();
console.log('audioDevice => ', audioDevice);
await audio.setSinkId(audioDevice.deviceId);
audio.play();
played = true;
selectBtn.textContent = 'pause';
});
audio.addEventListener('ended', () => {
played = false;
selectBtn.textContent = 'play';
});
</script>
</body>
</html>