切换系统声音 - 迅速

时间:2017-12-26 14:19:32

标签: swift xcode audio system-sounds

我想这样点击一个按钮就可以点击按钮,它会反复重复一遍又一遍地播放系统声音(不重叠声音),直到再次点击按钮为止 - 基本上,按钮将切换重复播放音频服务系统声音的开/关。

如果有人知道怎么做,我会非常感激。

由于

2 个答案:

答案 0 :(得分:0)

要执行此操作,请使用无限重复的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()
    }
}

答案 1 :(得分:0)

您可以使用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")
            }
        }
    }