Home > AI > IOS > AVFoundation >

play audio in the background mode

import SwiftUI
import AVFoundation


struct ContentView: View {
    var player = AVAudioPlayer()
 
    init() {
        do {
            player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "bensound-memories", ofType: "mp3")!))
            
            // background mode
            let s =  AVAudioSession.sharedInstance()
            do {
                try s.setCategory(.playback) // background mode
            } catch {
                print(error)
            }
            
         
        } catch {
            print(error)
        }
        
    }
    var body: some View {
        NavigationView {
            VStack {
                
                Button {
                    player.play()
                } label: {
                    Text("Play")
                }
                
                
                Button {
                    player.pause()
                } label: {
                    Text("Pause")
                }

                
                Button {
                    if player.isPlaying {
                        player.currentTime = 0
                        player.play()
                    } else {
                        player.play()
                    }
                } label: {
                    Text("Restart")
                }
            }
            
        }
    }
}

And enable the Background Mode in the Capability.

Background Modes
Modes: 
> Audio, AirPlay, and Picture in the Picture.

Leave a Reply