【发布时间】:2015-11-18 03:16:01
【问题描述】:
我正在开发一个 Iphone 键盘扩展程序,当点击一个字符时键盘会播放声音。我想为我的 buttonPressed 函数随机化声音。到目前为止,我只能为该功能发出一种声音,并且能够让 spacePressed 功能播放另一种声音。本质上,我希望 buttonPressed 函数从数组中播放随机声音。提前谢谢你...
import UIKit
import AVFoundation
class KeyboardViewController: UIInputViewController {
var keyboardView: UIView!
//sounds
var sound1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound1", ofType: "mp3")!)
var sound2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound2", ofType: "mp3")!)
var sound3 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound3", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
@IBOutlet var nextKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadInterface()
//prepare sounds
//audioPlayer.prepareToPlay()
}
func loadInterface(){
let keyboardNib = UINib(nibName: "KeyboardView", bundle: nil)
self.keyboardView = keyboardNib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.addSubview(self.keyboardView)
view.backgroundColor = self.keyboardView.backgroundColor
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
}
@IBAction func buttonPressed (sender: UIButton){
let title = sender.titleForState(.Normal)
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.insertText(title!)
audioPlayer = try! AVAudioPlayer(contentsOfURL: sound2)
//play sound
audioPlayer.play()
}
@IBAction func spacePressed (sender: UIButton){
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.insertText(" ")
audioPlayer = try! AVAudioPlayer(contentsOfURL: sound3)
audioPlayer.play()
}
@IBAction func deletePressed (sender: UIButton){
let proxy = textDocumentProxy as UITextDocumentProxy
proxy.deleteBackward()
}
@IBAction func capsLockPressed (sender: UIButton){
}
@IBAction func returnKeyPressed (sender: UIButton){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
}
}
【问题讨论】:
-
stackoverflow.com/questions/33754957/… 如何随机化数组索引