Управление воспроизведением музыки
Отправляйте подключённому устройству команды воспроизведения, переключения треков, отключения звука и изменения громкости.
Предварительные требования
- Устройство подключено и готово к работе.
- Устройство поддерживает
DeviceMusicControlAPI. - Явно заданная громкость находится в диапазоне от 0 до 100.
Реализация с помощью AI
Разработка с AI
Реализуйте этот сценарий с AI
Используйте официальный навык «Управление музыкой AIBuds» и адаптируйте сценарий к приложению.
Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/control-aibuds-music. Используйте этот навык, чтобы реализовать «Управление музыкой AIBuds» в данном iOS-проекте и проверить результат.Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Команды определены протоколом DeviceMusicControlAPI.
- Swift
- Objective-C
/// The protocol for device music control API.
protocol DeviceMusicControlAPI: DeviceAPI {
/// Starts or resumes music playback.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func playMusic(_ completion: AIBudsCompletionHandler?)
/// Pauses the currently playing music.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func pauseMusic(_ completion: AIBudsCompletionHandler?)
/// Skips to the next track in the playback queue.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func playNextMusic(_ completion: AIBudsCompletionHandler?)
/// Returns to the previous track in the playback queue.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func playPreviousMusic(_ completion: AIBudsCompletionHandler?)
/// Increases the playback volume by one step.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func musicVolumeUp(_ completion: AIBudsCompletionHandler?)
/// Decreases the playback volume by one step.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func musicVolumeDown(_ completion: AIBudsCompletionHandler?)
/// Mutes the playback volume.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func mute(_ completion: AIBudsCompletionHandler?)
/// Unmutes the playback volume.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func unmute(_ completion: AIBudsCompletionHandler?)
/// Sets the playback volume to a specific level.
/// - Parameters:
/// - volume: The desired volume level (0–100).
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func setMusicVolume(
_ volume: Int,
completion: AIBudsCompletionHandler?
)
}/// The protocol for device music control API.
@protocol AIBudsDeviceMusicControlAPI <AIBudsDeviceAPI>
/// Starts or resumes music playback.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)playMusicWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Pauses the currently playing music.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)pauseMusicWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Skips to the next track in the playback queue.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)playNextMusicWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Returns to the previous track in the playback queue.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)playPreviousMusicWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Increases the playback volume by one step.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)musicVolumeUpWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Decreases the playback volume by one step.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)musicVolumeDownWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Mutes the playback volume.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)muteWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Unmutes the playback volume.
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)unmuteWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
/// Sets the playback volume to a specific level.
/// - Parameters:
/// - volume: The desired volume level (0–100).
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the
/// operation was successful.
- (void)setMusicVolume:(NSInteger)volume completion:(AIBudsCompletionHandler _Nullable)completion;
@endМетоды экземпляра
| Метод | Назначение |
|---|---|
playMusic | Начать или продолжить воспроизведение. |
pauseMusic | Приостановить воспроизведение. |
playNextMusic | Перейти к следующему треку. |
playPreviousMusic | Перейти к предыдущему треку. |
musicVolumeUp | Увеличить громкость на один шаг. |
musicVolumeDown | Уменьшить громкость на один шаг. |
mute | Отключить звук. |
unmute | Включить звук. |
setMusicVolume | Задать громкость от 0 до 100. |
Параметры
| Параметр | Тип | Описание |
|---|---|---|
volume | Int / NSInteger | Требуемая громкость от 0 до 100. |
completion | AIBudsCompletionHandler? | Необязательный обработчик завершения. |
Параметры обратного вызова:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | Успешно ли выполнена команда. |
error | NSError? | Сведения об ошибке либо nil при успехе. |
Возвращаемое значение
Эти методы не возвращают значение напрямую.
Примеры использования
Воспроизведение
- Swift
- Objective-C
import AIBuds
guard let device = device as? DeviceMusicControlAPI else {
print("Device does not support music control")
return
}
device.playMusic { success, error in
guard success else {
print("Play failed: \(error?.localizedDescription ?? "Unknown error")")
return
}
print("Playback command succeeded")
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
id<AIBudsDeviceMusicControlAPI> device = (id<AIBudsDeviceMusicControlAPI>)self.device;
if ([device conformsToProtocol:@protocol(AIBudsDeviceMusicControlAPI)]) {
[device playMusicWithCompletion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Play failed: %@", error.localizedDescription);
return;
}
NSLog(@"Playback command succeeded");
}];
}Громкость воспроизведения
- Swift
- Objective-C
device.setMusicVolume(60) { success, error in
if !success {
print(error?.localizedDescription ?? "Volume update failed")
}
}[device setMusicVolume:60
completion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"%@", error.localizedDescription);
}
}];Обработка ошибок
Для каждой команды проверяйте success, а сведения об ошибке берите из error. Перед вызовом проверяйте заданную громкость: открытый контракт не гарантирует автоматическое ограничение диапазона.
Рекомендации
- Используйте точные имена SDK: не заменяйте методы обобщёнными
play,pause,nextTrackилиpreviousTrack. - Добавьте задержку для изменения громкости: демо SDK откладывает отправку значения ползунка, чтобы не создавать поток команд.
- Не смешивайте API громкости: этот протокол предназначен для управления воспроизведением, а
DeviceVolumeControlAPI— для отдельных каналов устройства. - Обновляйте интерфейс после успеха: отправка команды ещё не означает её успешного выполнения.
Примечания
- В протоколе нет команды остановки и отдельного свойства поддержки.
- Метаданные треков и содержимое очереди не входят в этот API.