mercredi 10 août 2016

How do I create an Random audio sound generator

Thanks for replying.

I am trying to make a program when I press a button once, two random sounds will play. I can get the random sounds to play if I press the button, but I am looking that if I press the button, the random sound will play differently each time.

I can paste the sounds together to hear them in the sequence I want them, but I would like swift to generate the sounds.

I thought of the AVqueplayer to make it as a playlist. I was thinking this can be like a pair of dice in an analogy. For example, if I were to throw the dice down, the random sounds will occur.

I am still a newbie, and tried to figure this out on my own, because it seemed so simple, but I am out of options now.

Here is what I got so far. This will play a random sound when I press the button each time.

import UIKit import AVFoundation

class ViewController: UIViewController {

var player: AVAudioPlayer = AVAudioPlayer()

var sounds = ["sound1", "sound2", "sound3"]

override func viewDidLoad() {
    super.viewDidLoad()  

}

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if event!.subtype == UIEventSubtype.motionShake {


        let randomNumber = Int(arc4random_uniform(UInt32(sounds.count)))
        let fileLocation = Bundle.main.path(forResource: sounds[randomNumber], ofType: "mp3")
        var error: NSError? = nil
        do { try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
        player.play()
        } catch {}           
    }
}

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

}




Aucun commentaire:

Enregistrer un commentaire