Активное шумоподавление
Читайте текущие настройки ANC подключённого устройства и изменяйте режим, уровни усиления и плавность перехода.
Предварительные требования
- Устройство подключено и готово к работе.
- Устройство поддерживает
DeviceANCAPI. - Перед включением элементов управления ANC значение
ancModeотличается от.unknown.
Реализация с помощью AI
Разработка с AI
Реализуйте этот сценарий с AI
Используйте официальный навык «Настройка шумоподавления AIBuds» и адаптируйте сценарий к приложению.
Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/configure-aibuds-anc. Используйте этот навык, чтобы реализовать «Настройка шумоподавления AIBuds» в данном iOS-проекте и проверить результат.Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds
import AIBudsFoundation#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Настройки и команды определены протоколом DeviceANCAPI.
- Swift
- Objective-C
/// The protocol for device API that supports Active Noise Cancellation (ANC).
protocol DeviceANCAPI: DeviceAPI {
/// The current Active Noise Cancellation (ANC) mode of the device.
var ancMode: ANCMode { get }
/// The current ANC gain value of the device.
var ancGain: NSNumber? { get }
/// The current transparency gain value of the device.
var transparencyGain: NSNumber? { get }
/// Indicates whether the ANC fade feature is currently enabled.
var isAncFadeOn: Bool { get }
/// Sets the Active Noise Cancellation (ANC) mode for the device.
/// - Parameters:
/// - mode: The desired ANC mode to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if the operation succeeded.
func setAncMode(
_ mode: ANCMode,
completion: AIBudsCompletionHandler?
)
/// Sets the ANC gain value for the device.
/// - Parameters:
/// - ancGain: The desired ANC gain value to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if the operation succeeded.
func setAncGain(
_ ancGain: Int,
completion: AIBudsCompletionHandler?
)
/// Sets the transparency gain value for the device.
/// - Parameters:
/// - transparencyGain: The desired transparency gain value to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if the operation succeeded.
func setTransparencyGain(
_ transparencyGain: Int,
completion: AIBudsCompletionHandler?
)
/// Enables or disables the ANC fade feature for the device.
/// - Parameters:
/// - isOn: A Boolean value indicating whether to enable (`true`) or disable (`false`) the ANC fade feature.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if the operation succeeded.
func setAncFadeOn(
_ isOn: Bool,
completion: AIBudsCompletionHandler?
)
}/// The protocol for device API that supports Active Noise Cancellation (ANC).
@protocol AIBudsDeviceANCAPI <AIBudsDeviceAPI>
/// The current Active Noise Cancellation (ANC) mode of the device.
@property(nonatomic, readonly) enum AIBudsANCMode ancMode;
/// The current ANC gain value of the device.
@property(nonatomic, readonly, strong) NSNumber *_Nullable ancGain;
/// The current transparency gain value of the device.
@property(nonatomic, readonly, strong) NSNumber *_Nullable transparencyGain;
/// Indicates whether the ANC fade feature is currently enabled.
@property(nonatomic, readonly) BOOL isAncFadeOn;
/// Sets the Active Noise Cancellation (ANC) mode for the device.
/// - Parameters:
/// - mode: The desired ANC mode to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if
/// the operation succeeded.
- (void)setAncMode:(enum AIBudsANCMode)mode
completion:(AIBudsCompletionHandler _Nullable)completion;
/// Sets the ANC gain value for the device.
/// - Parameters:
/// - ancGain: The desired ANC gain value to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if
/// the operation succeeded.
- (void)setAncGain:(NSInteger)ancGain completion:(AIBudsCompletionHandler _Nullable)completion;
/// Sets the transparency gain value for the device.
/// - Parameters:
/// - transparencyGain: The desired transparency gain value to apply.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if
/// the operation succeeded.
- (void)setTransparencyGain:(NSInteger)transparencyGain
completion:(AIBudsCompletionHandler _Nullable)completion;
/// Enables or disables the ANC fade feature for the device.
/// - Parameters:
/// - isOn: A Boolean value indicating whether to enable (`true`) or disable (`false`) the ANC
/// fade feature.
/// - completion: A closure that is called when the operation completes.
/// - success: Indicates whether the operation completed successfully.
/// - error: An optional error object that provides details if the operation failed; `nil` if
/// the operation succeeded.
- (void)setAncFadeOn:(BOOL)isOn completion:(AIBudsCompletionHandler _Nullable)completion;
@endСвойства
| Свойство | Тип | Описание |
|---|---|---|
ancMode | ANCMode | Текущий режим ANC. |
ancGain | NSNumber? | Текущий уровень ANC либо nil, если он недоступен. |
transparencyGain | NSNumber? | Текущий уровень прозрачности либо nil, если он недоступен. |
isAncFadeOn | Bool / BOOL | Включён ли плавный переход ANC. |
Методы экземпляра
| Метод | Назначение |
|---|---|
setAncMode | Изменить режим ANC. |
setAncGain | Изменить уровень ANC. |
setTransparencyGain | Изменить уровень прозрачности. |
setAncFadeOn | Включить или отключить плавный переход ANC. |
Параметры
| Параметр | Тип | Описание |
|---|---|---|
mode | ANCMode / AIBudsANCMode | .normal, .anc или .transparency. Не передавайте .unknown. |
ancGain | Int / NSInteger | Требуемый уровень ANC. Текущее демо использует диапазон 0...100; единый диапазон пока не гарантирован открытым SDK. |
transparencyGain | Int / NSInteger | Требуемый уровень прозрачности. Текущее демо использует диапазон 0...100; единый диапазон пока не гарантирован открытым SDK. |
isOn | Bool / BOOL | Нужно ли включить плавный переход ANC. |
completion | AIBudsCompletionHandler? | Необязательный обработчик завершения. |
Методы не возвращают значение напрямую. Обработчик завершения получает success и необязательный NSError.
Примеры использования
Чтение текущих настроек
- Swift
- Objective-C
import AIBuds
guard let device = device as? DeviceANCAPI,
device.ancMode != .unknown
else {
print("Device does not support ANC")
return
}
print("Mode: \(device.ancMode)")
print("ANC gain: \(device.ancGain?.intValue.description ?? "Unavailable")")
print("Transparency gain: \(device.transparencyGain?.intValue.description ?? "Unavailable")")
print("ANC fade: \(device.isAncFadeOn)")#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
id<AIBudsDeviceANCAPI> device = (id<AIBudsDeviceANCAPI>)self.device;
if (![device conformsToProtocol:@protocol(AIBudsDeviceANCAPI)] ||
device.ancMode == AIBudsANCModeUnknown) {
NSLog(@"Device does not support ANC");
return;
}
NSLog(@"Mode: %ld", (long)device.ancMode);
NSLog(@"ANC gain: %@", device.ancGain ?: @"Unavailable");
NSLog(@"Transparency gain: %@", device.transparencyGain ?: @"Unavailable");
NSLog(@"ANC fade: %@", device.isAncFadeOn ? @"On" : @"Off");Изменение режима ANC
- Swift
- Objective-C
device.setAncMode(.anc) { success, error in
guard success else {
print("Failed to change ANC mode: \(error?.localizedDescription ?? "Unknown error")")
return
}
print("ANC mode updated")
}[device setAncMode:AIBudsANCModeAnc
completion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Failed to change ANC mode: %@", error.localizedDescription);
return;
}
NSLog(@"ANC mode updated");
}];Изменение уровней и плавного перехода
Значения ниже соответствуют текущему демо SDK. Пересмотрите их, когда SDK опубликует ограничения для конкретных устройств.
- Swift
- Objective-C
device.setAncGain(60, completion: nil)
device.setTransparencyGain(40, completion: nil)
device.setAncFadeOn(true, completion: nil)[device setAncGain:60 completion:nil];
[device setTransparencyGain:40 completion:nil];
[device setAncFadeOn:YES completion:nil];Обработка ошибок
Если команда завершилась ошибкой, верните интерфейс к значениям, которые сейчас сообщает устройство, и покажите ошибку обработчика, если она доступна. Специальные коды ошибок ANC открытым API не определены.