添加声音

时间:2017-07-05 17:46:35

标签: xcode swift3 nsbundle

我试图创建一个简单的声板,当按下按钮时发出声音,但是当我使用此代码时

let url = NSURL(fileURLWithPath: Bundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

我收到“Bundle.mainBundle”错误或者它告诉我从“NSBundle”更改“Bundle”因为它已被重命名但是当我更正时我得到另一个错误说“不能为非功能类型调用值” '捆绑'“

我的整个代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {


let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

            audioPlayer.append(audioPlayer())
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

}

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

首先在Swift 3中mainBundle()变为main,但为什么不是真正的短路:

let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!

init方法已重命名为

let audioPlayer = try AVAudioPlayer(contentsOf: url)

并将下一行更改为:

audioPlayers.append(audioPlayer)