forked from raycast/script-commands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset-audio-device.swift
executable file
·229 lines (179 loc) · 5.82 KB
/
set-audio-device.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/usr/bin/swift
// Required parameters:
// @raycast.schemaVersion 1
// @raycast.title Set audio device
// @raycast.mode silent
// Optional parameters:
// @raycast.icon 🎧
// @raycast.argument1 { "type": "text", "placeholder": "Name" }
// @raycast.argument2 { "type": "text", "placeholder": "Type (i/o/b)", "optional": true }
// @raycast.packageName Audio
// Documentation:
// @raycast.description Sets the input (i), the output (o) or both (b) audio sources, based on name. If `both` is passed, but no input or output device is found with the given name, it will still try to set the other one. For example, if you're trying to set both to "External mic", which doesn't have an input source, it will still set the output to the mic; vice-versa for a speaker.
// @raycast.author Roland Leth
// @raycast.authorURL https://runtimesharks.com
// Change lines 29 and 30 if you'd like another default,
// which currently sets both when no parameter is passed.
let arguments = Array(CommandLine.arguments.dropFirst())
let query = arguments.first!
let changeType: DeviceType = arguments.count >= 2
? ["input", "i"].contains(arguments[1])
? .input
: ["output", "o"].contains(arguments[1])
? .output
: .both
: .both
import Foundation
import CoreAudio
// Based on https://stackoverflow.com/a/58618034/793916
// Equivalent of kAudioObjectPropertyElementMain to prevent SDK compatibility issues.
private let audioObjectPropertyElementMain: AudioObjectPropertyElement = 0
struct DeviceType: OptionSet {
static let input = DeviceType(rawValue: 1 << 0)
static let output = DeviceType(rawValue: 1 << 1)
static let both: DeviceType = [.input, .output]
let rawValue: Int
var value: String {
switch self {
case .input:
return "input"
case .output:
return "output"
case .both:
return "both"
default:
return ""
}
}
}
final class AudioDevice {
let audioDeviceID: AudioDeviceID
init(deviceID: AudioDeviceID) {
self.audioDeviceID = deviceID
}
var hasOutput: Bool {
var address = AudioObjectPropertyAddress(
mSelector: AudioObjectPropertySelector(kAudioDevicePropertyStreamConfiguration),
mScope: AudioObjectPropertyScope(kAudioDevicePropertyScopeOutput),
mElement: audioObjectPropertyElementMain)
var propSize = UInt32(MemoryLayout<CFString?>.size)
var result = AudioObjectGetPropertyDataSize(audioDeviceID, &address, 0, nil, &propSize)
if (result != 0) {
return false
}
let bufferList = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: Int(propSize))
defer {
bufferList.deallocate()
}
result = AudioObjectGetPropertyData(audioDeviceID, &address, 0, nil, &propSize, bufferList)
if (result != 0) {
return false
}
let buffers = UnsafeMutableAudioBufferListPointer(bufferList)
return buffers.contains { $0.mNumberChannels > 0 }
}
var name: String? {
var address = AudioObjectPropertyAddress(
mSelector: AudioObjectPropertySelector(kAudioObjectPropertyName),
mScope: AudioObjectPropertyScope(kAudioObjectPropertyScopeGlobal),
mElement: audioObjectPropertyElementMain)
var name: CFString? = nil
var propSize = UInt32(MemoryLayout<CFString?>.size)
let result = AudioObjectGetPropertyData(audioDeviceID, &address, 0, nil, &propSize, &name)
if (result != 0) {
return nil
}
return name as String?
}
}
func findDevices() -> [AudioDevice] {
var propSize: UInt32 = 0
var address = AudioObjectPropertyAddress(
mSelector: AudioObjectPropertySelector(kAudioHardwarePropertyDevices),
mScope: AudioObjectPropertyScope(kAudioObjectPropertyScopeGlobal),
mElement: audioObjectPropertyElementMain)
var result = AudioObjectGetPropertyDataSize(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&propSize)
if (result != 0) {
print("Error \(result) from AudioObjectGetPropertyDataSize")
return []
}
let numDevices = Int(propSize / UInt32(MemoryLayout<AudioDeviceID>.size))
var devids = Array<AudioDeviceID>(repeating: AudioDeviceID(), count: numDevices)
result = AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&address,
0,
nil,
&propSize,
&devids)
if (result != 0) {
print("Error \(result) from AudioObjectGetPropertyData")
return []
}
return (0..<numDevices).compactMap { i in
AudioDevice(deviceID: devids[i])
}
}
@discardableResult
func set(_ deviceType: DeviceType, to query: String) -> (Bool, String) {
let devices = findDevices()
guard
let device = devices.first(where: {
$0.name?.localizedCaseInsensitiveContains(query) == true
&& (deviceType.contains(.input) ? !$0.hasOutput : $0.hasOutput)
})
else {
return (false, query)
}
let deviceName = device.name ?? query
var deviceId = device.audioDeviceID
let deviceIdSize = UInt32(MemoryLayout.size(ofValue: deviceId))
let selector = deviceType.contains(.input)
? kAudioHardwarePropertyDefaultInputDevice
: kAudioHardwarePropertyDefaultOutputDevice
var deviceIdPropertyAddress = AudioObjectPropertyAddress(
mSelector: AudioObjectPropertySelector(selector),
mScope: AudioObjectPropertyScope(kAudioObjectPropertyScopeGlobal),
mElement: audioObjectPropertyElementMain)
let result = AudioObjectSetPropertyData(
AudioObjectID(kAudioObjectSystemObject),
&deviceIdPropertyAddress,
0,
nil,
deviceIdSize,
&deviceId)
if (result != 0) {
return (false, deviceName)
}
return (true, deviceName)
}
switch changeType {
case .input,
.output:
let i = set(changeType, to: query)
guard i.0 else {
print("Could not set \(changeType.value) to \(i.1)")
exit(1)
}
print("Set \(changeType.value) to \(i.1)")
case .both:
let i = set(.input, to: query)
let o = set(.output, to: query)
switch (i.0, o.0) {
case (false, false):
print("Could not set any device to \(i.1)")
case (true, false):
print("Set input to \(i.1)")
case (false, true):
print("Set output to \(i.1)")
case (true, true):
print("Set both to \(i.1) & \(o.1)")
}
default:
exit(1)
}