2016-03-06 169 views
1

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

我发现下面的代码,它编译,但按下按钮时,它什么也不做。有人可以看看它,看看有什么不对吗?在模拟器中播放应用程序时出现错误。

您可以找到下面的代码:

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

回答

0

做了一些小的变化,你的,现在它工作正常。

我正在使用一个音频播放器引用,在函数中设置,然后如果不为空,则播放它。

您还可以调用函数来播放声音,如果移动audioPlayer和.play()的方法

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

你的答案应该解释一下什么是错的,什么样的变化,你做。不要只是在没有解释的情况下发布代码。 – rmaddy

+0

你是对的,我会解释代码。 – UlyssesR

+0

谢谢!我会尝试使用这些代码,并会通知您。 – Henry