Code Examples for starting background audio from an AppIntent

Hi all,

I'm trying to update my app to use the AppIntent framework to play an audio file (loaded from the main bundle).

I tried implementing an a PlayMusicIntent using the AudioStartingIntent protocol, but have had no luck. The intent does run, and provides the dialog response, but the music doesn't start.

struct PlayMusicIntent: AudioStartingIntent {
    static let title:LocalizedStringResource = "Play Music"
    
    @MainActor
    func perform() async throws -> some IntentResult & ProvidesDialog {
        guard let musicPath = Bundle.main.url(forResource: "moonglow", withExtension: "mp3") else { fatalError("Could not load music file") }
        do {
            let musicPlayer = try AVAudioPlayer(contentsOf: musicPath)
            musicPlayer.numberOfLoops = -1
            musicPlayer.play()
            
            return .result(dialog: "Now Playing Moonglow")
        }catch {
            print(error)
            return .result(dialog: "There was an error playing the music: \(error.localizedDescription)")
        }
        
        return .result(dialog: "Cannot play music")
    }
}

And then add this in my App Shortcuts Provider:

AppShortcut(intent: PlayMusicIntent(), phrases: [
      "Play music with \(.applicationName)"
])

I do have Audio background mode enabled. I'm thinking I need to do something with the intent's return type, but there is not a lot of documentation or online examples to implement AudioStartingIntent

Any suggestions would be appreciated.

Thanks,

Scott

I'm doing tests for a similar situation, although I only need to play a short audio instead of a full song or playlist. I finally was able to make It work by awaiting the audio to be finished before returning in the perform() method. It looks like it's not your case but it might give you at least an idea.

Really very keen to understand how you've managed to get this working too - I have a button in my Widget, that I want to play a sound when pressed

Hey, I've finally got this working! I would say the key is to manage the playback in the app instead of the intent. For example, create a player object in AppDelegate that adds a notification observer for "play" requests. Then in the app intent post a "play" request notification. That should be received by the player object so it can then play what is requested.

A rudimentary code example is here: https://github.com/teaseaque/ManagingAudioWithIntents

Code Examples for starting background audio from an AppIntent
 
 
Q