1/* 2util.mjs - MIDI utility functions 3Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/midi/midi.mjs> 4This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. 5*/ 6 7import { Input, Output } from 'webmidi'; 8 9/** 10 * Get a string listing device names for error messages. 11 * @param {Input[] | Output[]} devices 12 * @returns {string} 13 */ 14export function getMidiDeviceNamesString(devices) { 15 return devices.map((o) => `'${o.name}'`).join(' | '); 16} 17 18/** 19 * Look up a device by index or name. Otherwise return a default device, or fail if none are connected. 20 * 21 * @param {string | number} indexOrName 22 * @param {Input[] | Output[]} devices 23 * @returns {Input | Output | undefined} 24 */ 25export function getDevice(indexOrName, devices) { 26 if (typeof indexOrName === 'number') { 27 return devices[indexOrName]; 28 } 29 const byName = (name) => devices.find((output) => output.name.includes(name)); 30 if (typeof indexOrName === 'string') { 31 return byName(indexOrName); 32 } 33 // attempt to default to first IAC device if none is specified 34 const IACOutput = byName('IAC'); 35 const device = IACOutput ?? devices[0]; 36 if (!device) { 37 if (!devices.length) { 38 throw new Error(`🔌 No MIDI devices found. Connect a device or enable IAC Driver.`); 39 } 40 throw new Error(`🔌 Default MIDI device not found. Use one of ${getMidiDeviceNamesString(devices)}`); 41 } 42 43 return device; 44}