JoeShmoe JoeShmoe - 6 months ago 52
Swift Question

Playing multiple sounds in swift

I am trying to add multiple buttons to play a dedicated sound ie;button 1 plays sound 1, button 2 plays sound 2, button 3 plays sound 3, and so on. I've tried using the below code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var PlaySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("tea-pot-whistle", ofType: "wav")!)
var Sound1audioPlayer = AVAudioPlayer()
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wind_1234", ofType: "wav")!)
var Sound2audioPlayer = AVAudioPlayer()
var pianoSound2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Evil_Laugh", ofType: "wav")!)
var Sound3audioPlayer = AVAudioPlayer()

@IBOutlet weak var Btn1 : UIButton!
@IBOutlet weak var Btn2 : UIButton!
@IBOutlet weak var Btn3 : UIButton!

@IBAction func likedThis(sender: UIButton) {

if (Btn1.tag == 1){
Sound1audioPlayer.play()
}
if(Btn2.tag == 2){
Sound2audioPlayer.play()
}
if (Btn3.tag == 3){
Sound3audioPlayer.play()
}



/*
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"givewater", CFSTR ("wav"), NULL);
UInt32 SoundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &SoundID);
AudioServicesPlaySystemSound(SoundID);*/

}


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Btn1.tag = 1;
Btn2.tag = 2;
Btn3.tag = 3;

Sound1audioPlayer = try! AVAudioPlayer(contentsOfURL: pianoSound)
Sound2audioPlayer = try! AVAudioPlayer(contentsOfURL: PlaySound)
Sound3audioPlayer = try! AVAudioPlayer(contentsOfURL: pianoSound2)

Sound1audioPlayer.prepareToPlay()
Sound2audioPlayer.prepareToPlay()
Sound3audioPlayer.prepareToPlay()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}


this code plays the sound but it plays all three depending on which button is pressed. I am new to swift, in objective c I had each IBAction written out for each button. Then I modified the code to tie all the buttons to a single action and I used tags to determine which button was pressed. Am I able to this type of consolidation with swift? any help would greatly appreciated.

Answer

replace your,

  if (Btn1.tag == 1){
    Sound1audioPlayer.play()
}
if(Btn2.tag == 2){
    Sound2audioPlayer.play()
}
if (Btn3.tag == 3){
    Sound3audioPlayer.play()
}

with

 if (sender.tag == 1){
    Sound1audioPlayer.play()
}
if(sender.tag == 2){
    Sound2audioPlayer.play()
}
if (sender.tag == 3){
    Sound3audioPlayer.play()
}

you should use sender.tag!! If you check btn.tag then every condition will become true!!

Hope this will help :)

Comments