Reputation: 45
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.
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()
}
}
Upvotes: 2
Views: 1500
Reputation: 2317
Did some small changes and your, and now it works fine.
I am using a single audioPlayer reference, setting in the function, and then if not null, playing it.
You can also call the function to play the sound, if you move the audioPlayer and the .play() to the method
import AVFoundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainButton1: UIButton!
var arrayOfSounds = ["sound1", "sound2", "sound3", "sound4"]
var audioPlayer : AVAudioPlayer?
func setupAudioPlayer(file: NSString, type: NSString){
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
}
@IBAction func buttonPressed(sender: AnyObject){
let range: UInt32 = UInt32(arrayOfSounds.count)
let number = Int(arc4random_uniform(range))
self.setupAudioPlayer(arrayOfSounds[number], type: "wav")
self.audioPlayer?.play()
}
}
Upvotes: 2