0
Swift新手。我试图控制我的应用程序播放背景音乐。我目前已经在我的MainTabController中启动了音乐。当我浏览其余的风险投资公司时,它会按预期发挥作用。但是,如果显示某些风险投资,我希望它停止。(Swift2.3)从另一个类访问类实例
我有我的MusicHelper类设置。
class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?
func playBackgroundMusic(file : String, repeats : Int) {
let aSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(file, ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOfURL:aSound)
audioPlayer!.numberOfLoops = repeats
audioPlayer!.prepareToPlay()
audioPlayer!.play()
} catch {
print("Cannot play the file")
}
}
func togglePlayer(){
if((audioPlayer?.playing) == true){
audioPlayer?.stop()
}else{
audioPlayer?.play()
}
}
}
我如何开始启动音乐在我的MainTabController:
class MainTabController: UINavigationController {
var bgMusic : MusicHelper = MusicHelper()
override func viewDidLoad() {
super.viewDidLoad()
// other code
bgMusic.playBackgroundMusic("music_background", repeats: -1)
}
}
我试图访问bgMusic的同一实例,但是它返回零。我的假设是我实际上正在创建一个MainTabController的新实例?如果是这样,我将如何去访问相同的MusicHelper实例?
class VideoViewController: OrientationLockedVC {
//Other code
var mVC : MainTabController = MainTabController()
func onImage() {
//other code
mVC.bgMusic.audioPlayer!.stop()
// other code
}
}
我没有得到任何明确的错误,但如果我设置一个断点,我可以清楚地看到,audioController为零。
感谢
这主要工作。谢谢。将其更改为公共静态。必须将MusicHelper.audioPlayer添加到其余的funcs中。虽然不能称之为你的建议。必须通过MusicHelper(bgMusic)的实例来调用它。我也用这个来触发sfx,不确定这是否有所作为,但无论如何,我终于可以正常工作了。再次感谢你。 – Ziast
不客气;) 在这个链接中,你会发现静态方法和变量的更多细节。 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html – cwilliamsz