Search code examples
swiftuimedia-playeravplayer

SwiftUI: showing AVPlayer playback (media) on locked screen


I have tried few iOS examples, but they seems not working for SwiftUI, for example https://medium.com/@quangtqag/background-audio-player-sync-control-center-516243c2cdd1

How can display control buttons and media info on locked screen in SwiftUI framework?

UPD: Adding example

import SwiftUI
import MediaPlayer
import AVFoundation

class ViewModel: ObservableObject {

@Published var isPlaying = false

private let audioSession = AVAudioSession.sharedInstance()
private let player = AVPlayer()

init() {
    if let path =
        Bundle.main.path(forResource: "5.mp3", ofType: nil) {
        let asset = AVAsset(url: URL(fileURLWithPath: path))
        let playerItem = AVPlayerItem(asset: asset)
        player.replaceCurrentItem(with: playerItem)
    }
    
    try! self.audioSession.setCategory(AVAudioSession.Category.playback)
    try! self.audioSession.setActive(true)
    
    setupRemoteTransportControls()
    setupNowPlaying()
    
}

func setupRemoteTransportControls() {
    let commandCenter = MPRemoteCommandCenter.shared()
    
    commandCenter.playCommand.isEnabled = true
    commandCenter.playCommand.addTarget { [unowned self] event in
        if !self.isPlaying {
            self.play()
            return .success
        }
        return .commandFailed
    }
    
    commandCenter.pauseCommand.isEnabled = true
    commandCenter.pauseCommand.addTarget { [unowned self] event in
        if self.isPlaying {
            self.pause()
            return .success
        }
        return .commandFailed
    }
    
}

func setupNowPlaying() {
    // Define Now Playing Info
    var nowPlayingInfo = [String : Any]()
    nowPlayingInfo[MPMediaItemPropertyTitle] = "My Movie"

    if let image = UIImage(named: "lockscreen") {
        nowPlayingInfo[MPMediaItemPropertyArtwork] =
            MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
        }
    }
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentItem?.currentTime().seconds
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = player.currentItem?.asset.duration.seconds
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate

    // Set the metadata
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}

func play() {
    isPlaying.toggle()
    player.play()
}

func pause() {
    isPlaying.toggle()
    player.pause()
}

}

struct ContentView: View {

@StateObject private var viewModel = ViewModel()

var body: some View {
    Button(action: {
        if viewModel.isPlaying {
            viewModel.pause()
        } else {
            viewModel.play()
        }
    }, label: {
        Image(systemName: viewModel.isPlaying ? "pause" : "play")
    })
}
}

I also tried to add beginReceivingRemoteControlEvents but it does not make any difference

struct PlayerApp: App {

@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

var body: some Scene {
    WindowGroup {
        ContentView()
    }
}

}

class AppDelegate: NSObject, UIApplicationDelegate {
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    application.beginReceivingRemoteControlEvents()
    return true
    
}
}

The audio is playing ok with the locked screen, it is just there is no playback controls and media info


Solution

  • I just implemented these two functions in an audiobook player app I'm working on and they work as outlined in Apple's documentation (and as you have coded). The only thing I can think of is perhaps try changing your AVAudioSession's category to:

    .playAndRecord
    

    My setCategory call looks like this:

    try audioSession.setCategory(.playAndRecord, mode: .spokenAudio, options: [.defaultToSpeaker, .allowAirPlay, .allowBluetoothA2DP])