我正在尝试将背景音乐实现到我用Xcode制作的应用程序中,在我使用的Swift的当前版本(4.2)中,我很难找到一个有效的解决方案。当前,当我从一个视图控制器切换到另一个视图控制器时,音乐将重新启动,但当我退出视图控制器时,这不会发生。
我将发布我目前正在编写的代码:
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")
}
}
}发布于 2019-02-26 22:15:43
假设你在你发布的两个相同的风投之间.
每当你在VC中加入MusicHelper.sharedHelper.playBackgroundMusic()时,你的音乐就会重新启动。
viewDidLoad在VC生命周期中只发生一次。当你解雇一个VC时,你不会调用它的viewDidLoad,这就是为什么音乐没有重新启动的原因。
关于VC生命周期的更多信息
https://developer.apple.com/documentation/uikit/uiviewcontroller
https://stackoverflow.com/questions/54894318
复制相似问题