2016-03-06 172 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