2017-10-29 109 views
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爲零。

感謝

回答

0

public static var audioPlayer: AVAudioPlayer?

變化var audioPlayer: AVAudioPlayer?並呼籲

if MusicHelper.audioPlayer != nil{ 
MusicHelper.audioPlayer.stop() 
} 
+0

這主要工作。謝謝。將其更改爲公共靜態。必須將MusicHelper.audioPlayer添加到其餘的funcs中。雖然不能稱之爲你的建議。必須通過MusicHelper(bgMusic)的實例來調用它。我也用這個來觸發sfx,不確定這是否有所作爲,但無論如何,我終於可以正常工作了。再次感謝你。 – Ziast

+0

不客氣;) 在這個鏈接中,你會發現靜態方法和變量的更多細節。 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html – cwilliamsz