gpt4 book ai didi

ios - 如何停止从另一个 ViewController 播放音频?

转载 作者:行者123 更新时间:2023-11-28 06:46:56 25 4
gpt4 key购买 nike

我在 xcode 中创建了四个 ViewController,当按下播放按钮时,每个 ViewController 都会播放不同的音频。如果我导航到另一个 View Controller 并按下该播放按钮...如何停止所有其他音频的播放,并确保新的音频混合成功播放?

下面详述的相同代码存在于四个 ViewController 中。唯一的区别是我创建了三个新的 musicPlayer 实例。它们是 musicPlayerSummer、musicPlayerWinter、musicPlayerAutumn。我为每个 View Controller 创建了新按钮。

如有任何建议,我们将不胜感激。

谢谢

导入 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)
}
}

最佳答案

为了解决这个问题,在appDelegate中声明audioPlayer

// inside AppDelegate
var audioPlayer : AVAudioPlayer? = nil

然后简单地在你的 viewController 中声明:

var audioPlayer : AVAudioPlayer? {
get {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
return appDelegate.audioPlayer
}
set {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.audioPlayer = newValue
}
}

关于ios - 如何停止从另一个 ViewController 播放音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com