Learn Courses My Dashboard

How do I automatically play background music in my app?

Hey guys! Sorry to keep posting in this forum too much, it’s just that Apple’s Swift Student Challenge is due today, and one of my features, is some music in the background. I’ve googled it, gone through countless tutorials, and still couldn’t fix the issue. Any help would be appreciated!

My audio manager file:

import Foundation
import AVKit

final class AudioManager {
    static let shared = AudioManager()
    var player: AVAudioPlayer?
    func startPlayer(track: String) {
        guard let url = Bundle.main.url(forResource: track, withExtension: "mp3") else {
            print("Resource not found: \(track).mp3")
        do {
            player = try AVAudioPlayer(contentsOf: url)
        } catch {
            print("Fail to initalize player", error)

My issue: How do I make music automatically play in the background? Because I’ve tried this and it doesn’t work:

import SwiftUI
import AVFoundation

struct ContentView: View {
    var body: some View {
        ZStack {
            NavigationView {
                VStack(alignment: .center) {
                        .frame(width: 300, height: 400)
                    Text("INSERT PLACEHOLDER TEXT ICI")
                    NavigationLink(destination: LangView()) {
                        Text("Get Started")
        .onAppear {
            AudioManager.shared.startPlayer(track: "Background")

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

The .onAppear doesn’t work, I’ve been trying to debug this before my submission tonight since last night. Please help, would really appreciate it.

Also, my music files aren’t corrupt and all. They work fine. The simulator doesn’t work even on full devices and simulator volume. I haven’t tested it on a regular device yet.

Don’t be sorry about posting! That’s what the forum is for!

Because this is SwiftUI, I’m thinking maybe AudioManager needs to be an ObservableObject?? Possibly? because it’s not holding the AVAudioPlayer in memory?

So you make AudioManager conform to ObservableObject and make player be a @Published variable

Yeah according to this article, that seems to fix it

Thank you I just tried it! It works like a charm!