我在xcode中創建了四個ViewController,每按一個播放按鈕時它們都會播放不同的音頻混合。如果我導航到另一個視圖控制器並按下該播放按鈕...如何停止播放其他所有音頻,並確保新的音頻混合播放成功?如何停止從另一個ViewController播放音頻?
下面詳細介紹的代碼存在於四個ViewController中。唯一的區別是我創建了三個新的musicPlayer實例。他們是musicPlayerSummer,musicPlayerWinter,musicPlayerAutumn。我爲每個viewcontroller創建了新的按鈕。
任何建議,將不勝感激。
謝謝
進口的UIKit 進口AVFoundation
類ViewControllerSpring:UIViewController的{
var musicPlayer: AVAudioPlayer!
var mySongs = ["1", "2", "3", "4"]
override func viewDidLoad() {
super.viewDidLoad()
initAudio()
// Do any additional setup after loading the view.
}
func initAudio() {
let path = NSBundle.mainBundle().pathForResource(mySongs[0], ofType: "mp3")!
do {
musicPlayer = try AVAudioPlayer(contentsOfURL: NSURL(string: path)!)
musicPlayer.prepareToPlay()
musicPlayer.numberOfLoops = -1
} catch let err as NSError {
print(err.debugDescription)
}
let session:AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
//catching the error.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func prefersStatusBarHidden() -> Bool {
return true
}
@IBAction func springPlayPressed(sender: UIButton) {
if musicPlayer.playing {
musicPlayer.stop()
// for normal state
sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
} else {
musicPlayer.play()
// for Highlighted state
sender.setImage(UIImage(named: "Pause.png"), forState: UIControlState.Normal)
}
}
}
有幾個方法。一種方法是委派,其他方式是PostNotification。如果只有一個玩家,那麼應該使用授權,如果更多的玩家停止,那麼應該使用Notification Observer。 – iMuzahid
同意,最佳做法與上述一致。但是,如果你想採取捷徑......(通常被認爲是不好的做法)......讓你的球員變得更加全球化,或者更好地使他們成爲單身。 – MikeG
爲什麼讓球員全球化是不好的做法? – hoboman