Перейти к основному содержимому

Управление воспроизведением музыки

Отправляйте подключённому устройству команды воспроизведения, переключения треков, отключения звука и изменения громкости.

Предварительные требования

  • Устройство подключено и готово к работе.
  • Устройство поддерживает DeviceMusicControlAPI.
  • Явно заданная громкость находится в диапазоне от 0 до 100.

Реализация с помощью AI

Разработка с AI

Реализуйте этот сценарий с AI

Используйте официальный навык «Управление музыкой AIBuds» и адаптируйте сценарий к приложению.

Прочитайте и выполните инструкции https://docs-aibuds.github.io/ru/skills/control-aibuds-music. Используйте этот навык, чтобы реализовать «Управление музыкой AIBuds» в данном iOS-проекте и проверить результат.
Открыть официальный навык

Справочник API

Фреймворк

AIBuds.xcframework

Импорт

Swift
import AIBuds

Протокол

Команды определены протоколом DeviceMusicControlAPI.

Swift
/// 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?
    )
}

Методы экземпляра

МетодНазначение
playMusicНачать или продолжить воспроизведение.
pauseMusicПриостановить воспроизведение.
playNextMusicПерейти к следующему треку.
playPreviousMusicПерейти к предыдущему треку.
musicVolumeUpУвеличить громкость на один шаг.
musicVolumeDownУменьшить громкость на один шаг.
muteОтключить звук.
unmuteВключить звук.
setMusicVolumeЗадать громкость от 0 до 100.

Параметры

ПараметрТипОписание
volumeInt / NSIntegerТребуемая громкость от 0 до 100.
completionAIBudsCompletionHandler?Необязательный обработчик завершения.

Параметры обратного вызова:

ИмяТипОписание
successBool / BOOLУспешно ли выполнена команда.
errorNSError?Сведения об ошибке либо nil при успехе.

Возвращаемое значение

Эти методы не возвращают значение напрямую.

Примеры использования

Воспроизведение

Swift
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")
}

Громкость воспроизведения

Swift
device.setMusicVolume(60) { success, error in
    if !success {
        print(error?.localizedDescription ?? "Volume update failed")
    }
}

Обработка ошибок

Для каждой команды проверяйте success, а сведения об ошибке берите из error. Перед вызовом проверяйте заданную громкость: открытый контракт не гарантирует автоматическое ограничение диапазона.

Рекомендации

  1. Используйте точные имена SDK: не заменяйте методы обобщёнными play, pause, nextTrack или previousTrack.
  2. Добавьте задержку для изменения громкости: демо SDK откладывает отправку значения ползунка, чтобы не создавать поток команд.
  3. Не смешивайте API громкости: этот протокол предназначен для управления воспроизведением, а DeviceVolumeControlAPI — для отдельных каналов устройства.
  4. Обновляйте интерфейс после успеха: отправка команды ещё не означает её успешного выполнения.

Примечания

  • В протоколе нет команды остановки и отдельного свойства поддержки.
  • Метаданные треков и содержимое очереди не входят в этот API.