How do you control the volume of iOS ApplicationMusicPlayer?

16 Views Asked by At

I need to duck the audio coming from ApplicationMusicPlayer (Apple Music) while playing a local file using AVAudioPlayer.

I've tried using the duckOthers option as follows, but it doesn't have any effect on the music player's volume:

/// The MusicKit player to use for Apple Music playback
let musicPlayer = ApplicationMusicPlayer.shared

// The regular audio player for local-file playback
var filePlayer: AVAudioPlayer?

let appAudioSession = AVAudioSession.sharedInstance()

do
{
        try appAudioSession.setCategory(.playAndRecord, mode: .default, options: .duckOthers)
        try appAudioSession.setActive(true)
...

File-player setup:

func loadAudioFile(audioFileURL: URL)
{
    do
    {
        try filePlayer = AVAudioPlayer(contentsOf: audioFileURL)
        filePlayer?.prepareToPlay()
        filePrepared = true
    }
    catch let error
    {
        filePrepared = false
        print("PlaybackManager loadAudioFile: \(error.localizedDescription)")
    }
}

Music-player setup:

func setSong(_ theSong: Song?) async throws
{
    if let newSong = theSong
    {
        if musicPlayer.state.playbackStatus == .playing
        {
            stop()
        }

        selectedSongID = newSong.id
        print("Setting the queue to \(newSong)")
        musicPlayer.queue = ApplicationMusicPlayer.Queue(for: [newSong])
        try await musicPlayer.prepareToPlay()
    }
    else
    {
        if musicPlayer.state.playbackStatus == .playing
        {
            stop()
        }
    }
}

Then attempt to play both:

filePlayer?.play()
try await musicPlayer.play()

They both play, but the music is way louder than the local file. Presumably "duckOthers" doesn't work because there's one session for the entire app, and ApplicationMusicPlayer is not considered "other." I've read that there can be only one session per application.

This is a fairly critical problem for my application, since Music content is always much louder than locally recorded content. Any insight appreciated.

0

There are 0 best solutions below