2

I want to use iOS app on Mac with M1. It mainly works as intended in "Designed for iPad" mode, except player controls do not appear in control center as they are on iOS. Here is the important part of the code that works perfect on iOS:

import AVFoundation
import MediaPlayer

class RemoteCommandHandler: NSObject {
    static let shared = RemoteCommandHandler()
    
    weak var delegate: MainVCDelegate?
    
    private var player: AVAudioPlayer?
    private let audioSession = AVAudioSession.sharedInstance()
    private let commandCenter = MPRemoteCommandCenter.shared()
    private var nowPlayingInfo = [String: Any]()
    
    private var obs: NSKeyValueObservation?

    func initPlayback() {
        if obs == nil {       
            do {
                try audioSession.setCategory(.playback, mode: .default, options: [])
                
                try audioSession.setActive(true)
            } catch {
                //error
            }
            
            obs = audioSession.observe( \.outputVolume ) { avSession, _ in
                self.delegate?.setVolume(avSession.outputVolume)
            }
            
            setupRemoteTransportControls()

            if player == nil {
            do {
                try player = AVAudioPlayer(contentsOf:
                    URL(fileURLWithPath: Bundle.main.path(forResource: "TestTrack", ofType: "m4a")!))
                player?.delegate = self
                player?.volume = 0
                player?.numberOfLoops = 1
            } catch let error as NSError {
                //error
            }
        }
        }
    }
    
    func setupNowPlaying() {
            nowPlayingInfo[MPMediaItemPropertyTitle] = TrackInfo.title.userFriendlyString()
            nowPlayingInfo[MPMediaItemPropertyArtist] = TrackInfo.artist.userFriendlyString()
            nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = TrackInfo.album.userFriendlyString()
            
            let image = NowPlayingInfo.getArtwork()
            var artwork: MPMediaItemArtwork
            artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
            nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork

            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = PlayerStatusInfo.isPlaying() ? 1 : 0
            nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = NowPlayingInfo.getDurationMs() / 1000
                            nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NowPlayingInfo.currentMs / 1000
            nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackProgress] = NowPlayingInfo.calculateProgress()
            
            MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    }
}

Would appreciate any suggestions on how to make it work on Mac.

dandepeched
  • 424
  • 5
  • 20

0 Answers0