【问题标题】:How I Programmed the Musik off and on Button?我如何对音乐开关进行编程?
【发布时间】:2025-12-01 22:40:01
【问题描述】:

我想开发一个小应用程序。但是几天以来,我一直在尝试制作 Musik off Button。也许你可以帮助我。 我是这样开始的。

func MusikAN (sender: UIButton!) {
    MusikEinUndAusSchalten.setBackgroundImage(MusikEin, forState: .Normal)
    MusikEinUndAusSchalten.addTarget(self, action: "MusikAus:", forControlEvents: .TouchUpInside)
}
func MusikAus (sender: UIButton!){
    MusikEinUndAusSchalten.setBackgroundImage(MusikAus, forState: .Normal)
    MusikEinUndAusSchalten.addTarget(self, action: "MusikAN:", forControlEvents: .TouchUpInside)
    audioPlayer.stop()
}

我用这个功能制作音乐。

func Musik (sender: UIButton) {

    var alertsound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Blub1", ofType: "mp3")!)

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error: NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: alertsound, error: &error)
    audioPlayer.prepareToPlay()
    audioPlayer.play()

}

但它不起作用。声音来了。 当你按下“MusikAus”按钮时,你必须听不到音乐,当你按下“MusikAn”按钮时,你必须再次听到音乐。

【问题讨论】:

  • 按下关闭按钮时会调用 MusikAus 函数吗?

标签: ios swift avaudiosession audio


【解决方案1】:

每次按下按钮时都调用 addTarget 是个坏主意(它是 ADD,而不是 SET)。就像第二次点击一样,您将同时调用 BOTH 方法,甚至可能多次调用。因此,要么在添加新的或更好的集合之前调用 removeTarget,然后使用按钮的选定状态在两种方法之间切换。 另外,MusikAN 方法甚至没有调用音频播放器上的东西,那么停止播放后它应该如何继续播放呢?

【讨论】:

    【解决方案2】:

    我更新代码也许现在是对的。

    func MusikAN (sender: UIButton!) {
        MusikEinUndAusSchalten.setBackgroundImage(MusikEin, forState: .Normal)
        MusikEinUndAusSchalten.removeTarget(self, action: "MusikAn:", forControlEvents: .TouchUpInside)
        MusikEinUndAusSchalten.addTarget(self, action: "MusikAus:", forControlEvents: .TouchUpInside)
        audioPlayer.start()
    }
    func MusikAus (sender: UIButton!){
        MusikEinUndAusSchalten.setBackgroundImage(MusikAus, forState: .Normal)
        MusikEinUndAusSchalten.removeTarget(self, action: "MusikAus:", forControlEvents: .TouchUpInside)
        MusikEinUndAusSchalten.addTarget(self, action: "MusikAN:", forControlEvents: .TouchUpInside)
        audioPlayer.stop()
    }
    

    【讨论】: