0

I want to make it so that a button can be clicked, which will start repeatedly playing a system sound over and over (without overlapping the sounds) until the button is clicked again - so essentially, the button will toggle the repeated playing of an audio services system sound on/off.

If anyone would know how to do this I would greatly appreciate it.

Thanks

D-A UK
  • 1,084
  • 2
  • 11
  • 24
  • Seems like [an XY problem](https://meta.stackexchange.com/q/66377/364493). Why do you want to do this? – Tamás Sengel Dec 26 '17 at 18:26
  • I was simplifying a task I am doing to make the question easier to understand. The long reason is that I want to make a timer and for the timer to run once the seconds reach 0 until the user taps a device physical . button or on the screen. – D-A UK Dec 26 '17 at 18:30

2 Answers2

0

To do this use an AVAudioplayer with infinite repeat, and then pause/play it when button is pressed. First make a audioPlayer variable, outside of any function:

var audioPlayer : AVAudioPlayer!

Then initialise the audioPlayer inside of viewDidLoad:

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)")
    }
}

Then inside a function linked to your button, in my case I named that function buttonPressed:

@IBAction func buttonPress(_ sender:AnyObject){
    if audioPlayer.isPlaying {
       audioPlayer.pause()
    }
    else {
       audioPlayer.play()
    }
}
Eric
  • 1,210
  • 8
  • 25
0

You can use AVFoundation and AVAudioPlayer to manage music and sound inside you application

Import following

import AVFoundation

Create a property of AVAudioPlayer to manage play/stop and add following code inside the scope of your music button

 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")
            }
        }
    }