【发布时间】:2015-11-16 23:28:12
【问题描述】:
我已经知道如何在按下按钮时触发声音。当按下同一个按钮时,我被困在触发随机声音上。由于音频播放器需要一个字符串,我生成了一个随机数,但不知道如何在播放器中插入该随机数。下面的代码真的坏了,所以请耐心等待,我只是卡住了。
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var mainButton: UIButton!
var sound1: AVAudioPlayer?
var sound2: AVAudioPlayer?
var sound3: AVAudioPlayer?
var sound4: AVAudioPlayer?
//There are many more sounds, but this is short for the example
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()
if let sound1 = self.setupAudioPlayerWithFile("sound1", type: "aif")
{self.sound1 = sound1}
if let sound2 = self.setupAudioPlayerWithFile("sound2", type: "aif")
{self.sound2 = sound2}
if let sound3 = self.setupAudioPlayerWithFile("sound3", type: "aif")
{self.sound3 = sound3}
if let sound4 = self.setupAudioPlayerWithFile("sound4", type: "aif")
{self.sound4 = sound4}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func buttonPressed(sender: AnyObject){
let audioArray: NSArray = ["1, 2, 3, 4"]
let range: UInt32 = UInt32(audioArray.count)
number = Int(arc4random_uniform(range))
sound(number)?.play()
}
}
【问题讨论】:
-
将 4 个字符串放入一个数组中,生成一个 1-4 的随机数,然后用它来设置您的音频播放器
-
“设置音频播放器”部分是我不知道该怎么做的地方
-
然后阅读该课程的 Apple 文档。