Настройка эквалайзера
Получите настройки эквалайзера от устройства, покажите их в интерфейсе и примените выбранную пользователем настройку.
Предварительные условия
- Устройство подключено и готово к работе.
- Устройство поддерживает
DeviceEqualizerAPI. - По возможности используйте настройку, возвращённую устройством.
Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds
import AIBudsFoundation#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Операции эквалайзера определены протоколом DeviceEqualizerAPI.
- Swift
- Objective-C
/// The protocol for device API that supports equalizer.
protocol DeviceEqualizerAPI: DeviceAPI {
/// All available preset and custom equalizer settings reported by the device.
var allEQSettings: [EQSettingModel] { get }
/// The currently active equalizer setting.
var eqSetting: EQSettingModel? { get }
/// Applies the specified equalizer setting to the device.
/// - Parameters:
/// - equalizerSetting: The equalizer configuration to be applied.
/// - completion: A closure that is invoked when the operation completes.
/// - success: `true` if the setting was successfully applied; otherwise `false`.
/// - error: An `NSError` object if an error occurs during the operation; otherwise `nil`.
func setEqualizer(
_ equalizerSetting: EQSettingModel,
completion: AIBudsCompletionHandler?
)
}/// The protocol for device API that supports equalizer.
@protocol AIBudsDeviceEqualizerAPI <AIBudsDeviceAPI>
/// All available preset and custom equalizer settings reported by the device.
@property(nonatomic, readonly, copy) NSArray<AIBudsEQSettingModel *> *_Nonnull allEQSettings;
/// The currently active equalizer setting.
@property(nonatomic, readonly, strong) AIBudsEQSettingModel *_Nullable eqSetting;
/// Applies the specified equalizer setting to the device.
/// - Parameters:
/// - equalizerSetting: The equalizer configuration to be applied.
/// - completion: A closure that is invoked when the operation completes.
/// - success: `true` if the setting was successfully applied; otherwise `false`.
/// - error: An `NSError` object if an error occurs during the operation; otherwise `nil`.
- (void)setEqualizer:(AIBudsEQSettingModel *_Nonnull)equalizerSetting
withCompletion:(AIBudsCompletionHandler _Nullable)completion;
@endМетод экземпляра
Применяет заданную настройку эквалайзера к устройству.
- Swift
- Objective-C
/// Applies the specified equalizer setting to the device.
/// - Parameters:
/// - equalizerSetting: The equalizer configuration to be applied.
/// - completion: A closure that is invoked when the operation completes.
/// - success: `true` if the setting was successfully applied; otherwise `false`.
/// - error: An `NSError` object if an error occurs during the operation; otherwise `nil`.
func setEqualizer(
_ equalizerSetting: EQSettingModel,
completion: AIBudsCompletionHandler?
)/// Applies the specified equalizer setting to the device.
/// - Parameters:
/// - equalizerSetting: The equalizer configuration to be applied.
/// - completion: A closure that is invoked when the operation completes.
/// - success: `true` if the setting was successfully applied; otherwise `false`.
/// - error: An `NSError` object if an error occurs during the operation; otherwise `nil`.
- (void)setEqualizer:(AIBudsEQSettingModel *_Nonnull)equalizerSetting
withCompletion:(AIBudsCompletionHandler _Nullable)completion;Параметры
| Параметр | Тип | Описание |
|---|---|---|
equalizerSetting | EQSettingModel | Настройка, которую нужно применить. |
completion | AIBudsCompletionHandler? | Необязательный обработчик завершения операции. |
Параметры обработчика:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | Применена ли выбранная настройка. |
error | NSError? | Сведения об ошибке или nil при успехе. |
Возвращаемое значение
Метод не возвращает значение напрямую. Результат передаётся через обработчик завершения.
Примеры использования
- Swift
- Objective-C
import AIBuds
import AIBudsFoundation
guard let device = device as? DeviceEqualizerAPI else {
print("Device does not support equalizer")
return
}
guard let selectedSetting = device.allEQSettings.first else {
print("The device did not provide an equalizer setting")
return
}
device.setEqualizer(selectedSetting) { success, error in
guard success else {
print("Failed to apply equalizer: \(error?.localizedDescription ?? "Unknown error")")
return
}
print("Equalizer applied: \(selectedSetting.name ?? "Unnamed setting")")
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
id<AIBudsDeviceEqualizerAPI> device = (id<AIBudsDeviceEqualizerAPI>)self.device;
if (![device conformsToProtocol:@protocol(AIBudsDeviceEqualizerAPI)]) {
NSLog(@"Device does not support equalizer");
return;
}
AIBudsEQSettingModel *selectedSetting = device.allEQSettings.firstObject;
if (selectedSetting == nil) {
NSLog(@"The device did not provide an equalizer setting");
return;
}
[device setEqualizer:selectedSetting
withCompletion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Failed to apply equalizer: %@", error.localizedDescription);
return;
}
NSLog(@"Equalizer applied: %@", selectedSetting.name ?: @"Unnamed setting");
}];Пользовательские настройки
Используйте пользовательский слот, сообщённый устройством. Его gains.count задаёт число полос устройства, а minimumGain и maximumGain — транспортный диапазон -12...12 dB. customSetting(index:gains:) сопоставляет индекс слота с режимом начиная от customModeStart и возвращает nil при неверных данных.
- Swift
- Objective-C
// A returned custom setting identifies a slot and its supported band count.
guard let reportedSetting = device.allEQSettings.first(where: \.isCustom),
let slot = reportedSetting.customIndex?.intValue
else {
return
}
// Supply one gain per reported band. Every value must be within -12...12 dB.
let gains = Array(repeating: 0, count: reportedSetting.gains.count)
guard let customSetting = EQSettingModel.customSetting(index: slot, gains: gains) else {
return
}
device.setEqualizer(customSetting, completion: nil)// A returned custom setting identifies a slot and its supported band count.
AIBudsEQSettingModel *reportedSetting = nil;
for (AIBudsEQSettingModel *setting in device.allEQSettings) {
if (setting.isCustom) {
reportedSetting = setting;
break;
}
}
if (reportedSetting.customIndex == nil) {
return;
}
// Supply one gain per reported band. Every value must be within -12...12 dB.
NSMutableArray<NSNumber *> *gains = [NSMutableArray array];
for (NSUInteger index = 0; index < reportedSetting.gains.count; index++) {
[gains addObject:@0];
}
AIBudsEQSettingModel *customSetting =
[AIBudsEQSettingModel customSettingWithIndex:reportedSetting.customIndex.integerValue
gains:gains];
if (customSetting == nil) {
return;
}
[device setEqualizer:customSetting withCompletion:nil];defaultBandCount — число полос встроенных профилей. Не заменяйте им другое число полос, сообщённое устройством.
Обработка ошибок
Обрабатывайте success == false и показывайте error, если он есть. Открытый API не определяет специальные коды ошибок эквалайзера.