【问题标题】:Toggling a system sound - swift切换系统声音 - 快速
【发布时间】:2017-12-26 14:19:32
【问题描述】:

我想让它可以点击一个按钮,这将开始重复一遍又一遍地播放系统声音(不重叠声音),直到再次点击按钮 - 所以本质上,该按钮将打开/关闭音频服务系统声音的重复播放。

如果有人知道如何做到这一点,我将不胜感激。

谢谢

【问题讨论】:

  • 好像an XY problem。为什么要这样做?
  • 我正在简化我正在做的一项任务,以使问题更容易理解。长期的原因是我想制作一个计时器,并让计时器在秒数达到 0 时运行,直到用户点击设备物理。按钮或屏幕上。

标签: swift xcode audio system-sounds


【解决方案1】:

为此,请使用无限重复的AVAudioplayer,然后在按下按钮时暂停/播放。 首先在任何函数的外部创建一个 audioPlayer 变量:

var audioPlayer : AVAudioPlayer!

然后在viewDidLoad里面初始化audioPlayer:

override func viewDidLoad() {
    super.viewDidLoad()

    guard let url = Bundle.main.path(forResource: "myOwnSound", ofType: "wav") else { //your own file name AND extension type of course
       print("file not found")
       return
    }
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        try audioPlayer = AVAudioPlayer(contentsOf: URL(string: url)!)
        audioPlayer!.prepareToPlay()
        audioPlayer.numberOfLoops = -1
    } catch let error as NSError {
        print("error while initialising sound: \(error)")
    }
}

然后在链接到您的按钮的函数中,在我的例子中,我将该函数命名为 buttonPressed:

@IBAction func buttonPress(_ sender:AnyObject){
    if audioPlayer.isPlaying {
       audioPlayer.pause()
    }
    else {
       audioPlayer.play()
    }
}

【讨论】:

    【解决方案2】:

    您可以使用AVFoundationAVAudioPlayer 来管理音乐和 应用程序内部的声音

    导入关注

    import AVFoundation
    

    创建 AVAudioPlayer 的属性来管理播放/停止,并在音乐按钮的范围内添加以下代码

     var player : AVAudioPlayer?
    
    @IBAction func openListAction(_ sender: UIButton) {
           // moveToGame()
            if sender.isSelected {
                sender.isSelected = false
                player?.stop()
            }
            else {
                sender.isSelected = true
                let bundle = Bundle.init(for: self.classForCoder)
                let path = bundle.path(forResource: "soundFileName", ofType : "soundFileExtension")! //.mp3, .caf etc
                let url = URL(fileURLWithPath : path)
                do {
                    player = try AVAudioPlayer(contentsOf: url)
                    player?.play()
    
                } catch {
                    print ("Error to load music")
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多