2014-10-27 70 views
1

任何人都可以幫助我得到這個工作我是一個noob programer,我無法找到一種方法來做到這一點。需要幫助將音頻文件添加到快速按鈕

代碼如下

import UIKit 

class ViewController: UIViewController { 

    @IBAction func pistolButton(sender: AnyObject) { 

    } 

    override func viewDidLoad() { // I want my audio file to play when button is tapped 
     super.viewDidLoad() 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 

    } 
} 
+0

請編輯您的代碼以獲得某種感覺,過多的空白空函數並不是一個好問題。請參閱幫助中心獲取有關詢問優質問題的指導。 – Ajean 2014-10-27 01:29:45

回答

3

首先將您的聲音拖到您的項目中,並根據需要選擇複製到目的地,並選中「添加到目標」到您的應用程序。創建一個功能的發揮你的聲音,你也需要在你的代碼的開頭添加進口AVFoundation波紋管:

import AVFoundation 

let beepSoundURL = NSBundle.mainBundle().URLForResource("beep", withExtension: "aif")! 
var beepPlayer = AVAudioPlayer() 
func playMySound(){ 
    beepPlayer = AVAudioPlayer(contentsOfURL: beepSoundURL, error: nil) 
    beepPlayer.prepareToPlay() 
    beepPlayer.play() 
} 

@IBAction func pistolButton(sender: AnyObject) { 
    playMySound() 
} 
3

有堆棧溢出了很多不錯的代碼:

Playing a sound with AVAudioPlayer

下面是一些示例代碼:

import AVFoundation 
var audioPlayer: AVAudioPlayer? 

if let path = NSBundle.mainBundle().pathForResource("mysound", ofType: "aiff") { 
    audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), fileTypeHint: "aiff", error: nil) 

    if let sound = audioPlayer { 
     sound.prepareToPlay() 
     sound.play() 
    } 
} 

從這個位置:

http://www.reddit.com/r/swift/comments/28izxl/how_do_you_play_a_sound_in_ios/

0

斯威夫特3

語法如下內容:

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    var audioPlayer = AVAudioPlayer() 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     // address of the music file 
     let music = Bundle.main.path(forResource: "Music", ofType: "mp3") 

     do { 
      audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music!)) 
     } 
     catch{ 
      print(error) 
     } 
    } 
    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
    @IBAction func play(_ sender: AnyObject) { 
     audioPlayer.play() 
    } 
    @IBAction func stop(_ sender: AnyObject) { 
     audioPlayer.stop() 
    } 
}