JoeShmoe JoeShmoe - 1 year ago 153
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){
if(Btn2.tag == 2){
if (Btn3.tag == 3){

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


override func 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)



override func 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 Source

replace your,

  if (Btn1.tag == 1){
if(Btn2.tag == 2){
if (Btn3.tag == 3){


 if (sender.tag == 1){
if(sender.tag == 2){
if (sender.tag == 3){

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

Hope this will help :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download