ryohei ryohei - 7 months ago 15
Swift Question

How to deactivate playing a sound

I have been trying to figure out how to deactivate playing a sound. I tried to attached a

removeAtionWithKey
with a sound action, and it seems to be working fine, but the sound does not stop to play. Is this because I am using action in
SpriteKit
?

If this problem is solved here instead of importing
AVFoundation
, then could you give me some examples to stop a sound from being played? Or, if importing
AVFoundation
is preferred in this case, could you provide me with some code as well.

Answer

Here's an example of how to use AVFoundation.

import Foundation
import AVFoundation

var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {

    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")

    if (url == nil) {
        print("Could not find the file \(filename)")
    }

    do { backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) } catch let error as NSError { print(error.debugDescription)}

    if backgroundMusicPlayer == nil {
        print("Could not create audio player")
    }

    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}

var Sound: AVAudioPlayer!

func playSound(filename: String) {

    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "wav")

    if (url == nil) {
        print("Could not find the file \(filename)")
    }

    do { Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) } catch let error as NSError { print(error.debugDescription)}

    if Sound == nil {
        print("Could not create audio player")
    }

    Sound.prepareToPlay()
    Sound.play()
}

And here's what you want to achieve (if I understood well):

@IBAction func MusicButton(sender: UIButton) {
    if backgroundMusicPlayer.playing {
        backgroundMusicPlayer.stop()
    }
    else {
        playBackgroundMusic("SomeMusicName")
    }
}

Stopping the music with AVFoundation is as easy as .stop() ^^!

Comments