2014-10-27 75 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() 
    } 
}