Home > AI > IOS > AVFoundation >

play audio in the background mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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.

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

Leave a Reply