我需要创建一个按钮,当我按下它时,只播放一个声音。当我再次按它时,我想要一个不同的声音来玩。我有4个声音,我想随机播放。因此,当我按下按钮时,让我说8次,我会随机听到8个声音。
我将声音文件名放在一个数组中并实现arc4random随机化。我正在使用AVFoundation以及我遇到困难的地方。我不知道怎么玩这个阵列。
我知道如何播放1个声音,但不知道如何在按钮中实现此声音。任何人都有任何想法?
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["sound_1.mp3", "sound_2.mp3"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
@IBAction func tap(sender: UIButton) {
// Audio code?
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
编辑:
@IBAction func tap(sender: UIButton) {
let soundFilenames = ["Sound1.mp3", "Sound2.mp3"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
var audioPlayer : AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
编辑2:
var audioPlayer : AVAudioPlayer?
@IBAction func tap(sender: UIButton) {
let soundFilenames = ["Sound1", "Sound2"]
let randomIndex = Int(arc4random_uniform(UInt32(soundFilenames.count)))
let selectedFilename = soundFilenames[randomIndex]
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
答案 0 :(得分:0)
如果这是您的确切复制/粘贴代码,您的let声明语句可以使用校对。
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilename", ofType: "mp3")!)
不
let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("selectedFilemane", ofType: "mp3")!)
你提到你知道怎么播放声音,但是你还用这段代码完成了吗?