I am trying to implement background music into an app I am making in Xcode, I am having trouble finding a solution that works in the current version of Swift I'm using (4.2). Currently when I segue from one view controller to another the music will restart, but this doesn't happen when I dismiss the view controller.
I will post the code I'm working on so far:
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer : AVAudioPlayer?
var selectedSoundFileName : String = ""
let phonicSoundArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "ai", "ar", "ch", "ck", "ee", "ie", "ng", "oa", "oi", "oo", "or", "ou", "ph", "qu", "sh", "ss", "th", "ue"]
override func viewDidLoad() {
super.viewDidLoad()
MusicHelper.sharedHelper.playBackgroundMusic()
}
@IBAction func dismissCurrentView(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
//== Phonic audio playback =================
@IBAction func phonicPracticeButtonPressed(_ sender: AnyObject) {
selectedSoundFileName = phonicSoundArray[sender.tag - 1]+".mp3"
let path = Bundle.main.path(forResource: selectedSoundFileName, ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer?.play()
} catch {
print("Couldn't load audio")
}
}
}
BGMSingleton.swift
import Foundation
import AVFoundation
class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?
func playBackgroundMusic() {
let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "BGM", ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
audioPlayer!.numberOfLoops = -1
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
catch {
print("Cannot play the file")
}
}
}