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")
return
}
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} 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) {
Image("temple")
.resizable()
.scaledToFit()
.frame(width: 300, height: 400)
Text("TITLE")
.bold()
.font(.title)
Text("INSERT PLACEHOLDER TEXT ICI")
.bold()
NavigationLink(destination: LangView()) {
Text("Get Started")
.font(.headline)
.foregroundColor(.white)
.padding(.vertical,10)
.padding(.horizontal,20)
.background(Color.black)
.cornerRadius(25)
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
.onAppear {
AudioManager.shared.startPlayer(track: "Background")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
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.