Sound game Swift 3

Ok, I looked through this and tried many different ways to reproduce the sound at the click of a button.

How can I play the sound when I press the button in quick mode 3? I have a sound in a folder called Sounds and the name is ClickSound.mp3

+14
swift3 avfoundation avaudioplayer
Nov 15 '16 at 4:35
source share
4 answers

User below this function

//MARK:- PLAY SOUND func playSound() { let url = Bundle.main.url(forResource: "ClickSound", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOf: url) guard let player = player else { return } player.prepareToPlay() player.play() } catch let error as NSError { print(error.description) } } 

import AudioToolbox import AVFoundation first

Hope it works :)

+15
Nov 15 '16 at 5:58
source share

You must leave the player at the disposal, get it in the property of the controller of your kind.

The only real catch is that you must store your player as property or another variable that will not be immediately destroyed - if you are not, the sound will stop immediately.

source:

 var player : AVAudioPlayer? func playSound(){ let path = Bundle.main.path(forResource: "alert", ofType:"mp3")! let url = URL(fileURLWithPath: path) do { let sound = try AVAudioPlayer(contentsOf: url) self.player = sound sound.numberOfLoops = 1 sound.prepareToPlay() sound.play() } catch { print("error loading file") // couldn't load file :( } } 
+13
Feb 01 '17 at 19:53 on
source share

You might want to use SwiftySound . This makes it easy to play sounds in Swift 3.

 Sound.play(file: "ClickSound.mp3") 
+5
Feb 22 '17 at 13:17
source share

An easier way to do this is to put the following line of code in the button you clicked (Note: it only works in a set of sprites):

 run(SKAction.playSoundFileNamed("ClickSound.mp3", waitForCompletion: false)) 

Hope this helps :)

+3
Feb 12 '17 at 19:27
source share



All Articles