需要帮助在swift中将音频文件添加到按钮

时间:2014-10-27 01:19:47

标签: xcode swift xcode6

任何人都可以帮助我开始工作我是一个菜鸟程序员,我找不到办法做到这一点。

以下代码

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

    }
}

3 个答案:

答案 0 :(得分:3)

Stack Overflow上有很多相当不错的代码:

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/

答案 1 :(得分: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()
}

答案 2 :(得分:0)

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