Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement getDeviceByUID method #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,5 @@ public/
# DynamoDB Local files
.dynamodb/

# End of https://www.gitignore.io/api/node
# End of https://www.gitignore.io/api/node.vscode
.vscode
24 changes: 24 additions & 0 deletions Sources/audio-devices/AudioDevices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import CoreAudio
struct AudioDevice: Hashable, Codable, Identifiable {
enum Error: Swift.Error {
case invalidDeviceId
case invalidDeviceUID
case invalidDevice
case volumeNotSupported
case invalidVolumeValue
Expand Down Expand Up @@ -227,6 +228,29 @@ extension AudioDevice {
all.filter { $0.isOutput }
}

static func getDeviceIDByUID(deviceUID: String) throws -> AudioObjectID {
var deviceUIDCFString = deviceUID as CFString
var deviceID = kAudioDeviceUnknown
var propertyAddress = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDeviceForUID, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMaster)

let dataSize_CFString = UInt32(MemoryLayout<CFString>.stride)
let dataSize_AudioObjectID = UInt32(MemoryLayout<AudioObjectID>.stride)

var translation = AudioValueTranslation(
mInputData: &deviceUIDCFString, // Warning: "Inout expression creates a temporary pointer, but argument 'mInputData' should be a pointer that outlives the call to 'init(mInputData:mInputDataSize:mOutputData:mOutputDataSize:)'"
mInputDataSize: dataSize_CFString,
mOutputData: &deviceID, // Warning: "Inout expression creates a temporary pointer, but argument 'mOutputData' should be a pointer that outlives the call to 'init(mInputData:mInputDataSize:mOutputData:mOutputDataSize:)'"
mOutputDataSize: dataSize_AudioObjectID
)
var specifierSize = UInt32(MemoryLayout<AudioValueTranslation>.stride)
let result = AudioObjectGetPropertyData(UInt32(kAudioObjectSystemObject), &propertyAddress, 0, nil, &specifierSize, &translation)
guard result == kAudioHardwareNoError, deviceID != kAudioDeviceUnknown else {
throw Error.invalidDeviceUID
}

return deviceID
}

static func getDefaultDevice(for deviceType: DeviceType) throws -> Self {
var deviceId: AudioDeviceID = 0

Expand Down
44 changes: 43 additions & 1 deletion Sources/audio-devices/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,21 @@ func getDevice(deviceId: Int) throws -> AudioDevice {
}
}

func getDeviceByUID(deviceUID: String) throws -> AudioDevice {
do {
let deviceId = try AudioDevice.getDeviceIDByUID(deviceUID: deviceUID)
return try AudioDevice(withId: UInt32(deviceId))
} catch AudioDevice.Error.invalidDeviceUID {
print("No device exists with uid \(deviceUID)", to: .standardError)
exit(1)
} catch AudioDevice.Error.invalidDeviceId {
print("No device exists with uid \(deviceUID)", to: .standardError)
exit(1)
} catch {
throw error
}
}

final class ListCommand: Command {
let name = "list"
let shortDescription = "List the available audio devices"
Expand Down Expand Up @@ -94,6 +109,32 @@ final class GetCommand: Command {
}
}

final class GetByUIDCommand: Command {
let name = "getByUID"
let shortDescription = "Get a device by its UID"

@Flag("--json", description: "Print the result in JSON format")
var json: Bool

@Param var deviceUID: String

func execute() throws {
let device = try getDeviceByUID(deviceUID: deviceUID)

if json {
do {
print(try toJson(device))
} catch {
print("{}")
}

return
}

printDevice(device)
}
}

final class OutputGroup: CommandGroup {
let shortDescription = "Get or set the default output device"
let name = "output"
Expand Down Expand Up @@ -265,7 +306,7 @@ final class SetVolumeCommand: Command {
@Param var volume: Double

func execute() throws {
var device = try getDevice(deviceId: deviceId)
let device = try getDevice(deviceId: deviceId)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

small fix for warning during compilation.


do {
try device.setVolume(volume)
Expand Down Expand Up @@ -342,6 +383,7 @@ let audioDevices = CLI(name: "audio-devices")
audioDevices.commands = [
ListCommand(),
GetCommand(),
GetByUIDCommand(),
OutputGroup(),
InputGroup(),
SystemGroup(),
Expand Down
30 changes: 28 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export const getDevice: {
const device = await getDevice(73);
```
*/
(): Promise<Device>;
(deviceId: number): Promise<Device>;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typescript definition fix, not related to the main purpose of this PR, sorry.


/**
Get an audio device by ID.
Expand All @@ -103,7 +103,33 @@ export const getDevice: {
const device = getDevice.sync(73);
```
*/
sync: () => Device;
sync: (deviceId: number) => Device;
};

export const getDeviceByUID: {
/**
Get an audio device by UID.

@returns A promise that resolves with the device.

@example
```
const device = await getDeviceByUID("BGMDevice");
```
*/
(deviceUID: string): Promise<Device>;

/**
Get an audio device by ID.

@returns The device.

@example
```
const device = getDevice.sync(73);
```
*/
sync: (deviceId: number) => Device;
};

export const getOutputDevices: {
Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ generateExport('getOutputDevices', () => ['list', '--output', '--json'], parseSt

generateExport('getDevice', deviceId => ['get', '--json', deviceId], parseStdout);

generateExport('getDeviceByUID', deviceUID => ['getDeviceByUID', '--json', deviceUID], parseStdout);

generateExport('getDefaultOutputDevice', () => ['output', 'get', '--json'], parseStdout);

generateExport('getDefaultInputDevice', () => ['input', 'get', '--json'], parseStdout);
Expand Down