My background music plays once the view controller has loaded. which is great, however every time the user returns to that screen it plays again. and layers itself into a incoherent mess. I need the music to play once and continue to play until the user turns it off in the settings.
As I understand from the code i've written. Once the view loads in creates the audioPlayer
it then checks to see if the boolean isPlaying
is set to false
. If it is then it executes the playMusic
function. if its set to true
it should do nothing. I am confused on why it plays the music again on top of the previous iteration.
Could it be creating the audio player every time the view is loaded? if so how would i go about fixing that?
Once the app is loaded the user is presented with a start screen. the music starts playing there.
They then press either start, purchase hints, or settings. in order to go back to the previous screen you hit a back button. which the way the design of the app is setup, always takes you back to the start screen. the segues are just set up in that. i control dragged to the next view controller and chose the show
option.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
@IBOutlet weak var musicToggle: UIButton!
var isPlaying = false
@IBAction func musicTogglebtn(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "weiss", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
if isPlaying == false {
playMusic()
} else {
return
}
}
func playMusic() {
audioPlayer.play()
isPlaying = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}