dimanche 6 mars 2016

Play Random Sounds when a button is pressed Swift 2.0

Good Morning Community,

I am new to swift and working on my first app. I have all the code for the app done except for this: I want to make a button play random sound files when pressed.

I found the following code, which it compiles but the button, when pressed, it doesn't do anything. Can someone take a look at it and see what is wrong? I get a time out error when playing the app in the simulator.

Thanks! You can find the code below:

import AVFoundation
import UIKit

    class ViewController: UIViewController {


    @IBOutlet weak var mainButton1: UIButton!

    // PUT SOUNDS AS STRINGS IN ARRAY
    var arrayOfSounds = ["sound1", "sound2", "sound3", "sound4"]

    // Different Block of code below.
    var audioPlayer: AVAudioPlayer = AVAudioPlayer()

    func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {

        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        let url = NSURL.fileURLWithPath(path!)

        var audioPlayer : AVAudioPlayer?

        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
        } catch {
            print("Player not available")
        }
        return audioPlayer
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

}

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

    @IBAction func buttonPressed(sender: AnyObject){
        let range: UInt32 = UInt32(arrayOfSounds.count)
        let number = Int(arc4random_uniform(range))

        let sound = self.setupAudioPlayerWithFile(arrayOfSounds[number], type: "wav")
        sound!.play()
    }
}




Aucun commentaire:

Enregistrer un commentaire