按下按钮时播放随机声音Swift 2.0

时间:2016-03-06 15:38:37

标签: ios swift file audio random

我已完成应用程序的所有代码,除此之外:我想在按下时按下按钮播放随机声音文件。

我找到了以下代码,它编译但是按钮,按下时,它没有做任何事情。有人可以看看它,看看有什么问题吗?在模拟器中播放应用程序时出现超时错误。

您可以在下面找到以下代码:

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()
    }
}

1 个答案:

答案 0 :(得分:1)

做了一些小改动和你的,现在它工作正常。

我正在使用单个audioPlayer引用,在函数中设置,然后如果不为null,则播放它。

如果将audioPlayer和.play()移动到方法

,也可以调用该函数播放声音
xi