DEV Community

Masui Masanori
Masui Masanori

Posted on

[Electron] Play audio from a specific destination

Project files

ElectronSample
L clients
L ts
L audio.page.ts
L sound
L sample.mp4
L views
L js
L clients
L audio.page.js
L playAudio.html
L forge.config.js
L main.ts
L package-lock.json
L package.json
L preload.ts
L tsconfig.json
L webpack.config.js

Samples

playAudio.html



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Play audio</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
<audio id="audio_player" src="../sound/sample.mp3"></audio>
<button onclick="Page.playUsb()">Play USB Headphone</button>
<button onclick="Page.playHeadphoneJack()">Play Headphone Jack</button>
<button onclick="Page.stop()">Stop</button>
<script src="./js/clients/audio.page.js"></script>
<script>Page.init();</script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode




audio.page.ts




let audioElement: HTMLAudioElement;
export async function init() {
audioElement = document.getElementById("audio_player") as HTMLAudioElement;
audioElement.loop = true;
}
export async function playUsb() {
const usbHeadphoneId = await getDeviceId("usb");
if(usbHeadphoneId != null) {
(audioElement as any).setSinkId(usbHeadphoneId);
audioElement.play();
}
}
export async function playHeadphoneJack() {
const headphoneId = await getDeviceId("headphone");
if(headphoneId != null) {
(audioElement as any).setSinkId(headphoneId);
audioElement.play();
}
}
export function stop() {
audioElement.pause();
}
async function getDeviceId(key: string): Promise<string|null> {
try {
for(const d of await navigator.mediaDevices.enumerateDevices()) {
if(d.kind !== "audiooutput") {
continue;
}

if(d.label.toLowerCase().includes(key)) {
return d.deviceId;
}
}
}catch(ex) {
console.error(ex);
}
return null;
}

Enter fullscreen mode Exit fullscreen mode




Get device info by navigator.mediaDevices.enumerateDevices()

Image description

Resources

Top comments (0)