MaxRyan_97
MaxRyan_97

Reputation: 3

Playing sound effect in Xcode

I have created a button in Xcode that plays a short sound effect. I am not able to retrigger the button/sound, while it's playing. Therefore I have to wait until the sound has faded to repeat the effect. My intention is that every time I press the button, the sound effect starts to play, even if it is still fading out. Does anybody know how to achieve this? I am using XCode 11.6. My code is below. Many thanks in advance.

import UIKit import AVFoundation

class ViewController: UIViewController {

var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
        audioPlayer.prepareToPlay()
    } catch {
        print(error)
    }
}

@IBAction func Play(_ sender: Any) {
    audioPlayer.play()
}

}

Upvotes: 0

Views: 489

Answers (2)

Masoud Roosta
Masoud Roosta

Reputation: 475

if I understand correctly you want to prevent play again when sound is playing and just play sound when it finished already so you can make condition according sound is playing or not (try it in your button action):

 if audioPlayer.isPlaying(){
   // your statement when sound is playing in other word nothing to do
 }else{
   // your statement when sound is not playing and you want to start play
      audioPlayer.play()
 }

https://developer.apple.com/documentation/avfoundation/avaudioplayer/1390139-isplaying

Upvotes: 0

Frankenstein
Frankenstein

Reputation: 16341

You could just initialize the audioPlayer in Play method instead of viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func Play(_ sender: Any) {
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch {
        print(error)
    }
}

Upvotes: 1

Related Questions