我想用Swift播放一个声音。
我的代码在Swift 1.0中工作,但现在在Swift 2或更新版本中不再工作。
override func viewDidLoad() {
super.viewDidLoad()
let url:NSURL = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil)
} catch _{
return
}
bgMusic.numberOfLoops = 1
bgMusic.prepareToPlay()
if (Data.backgroundMenuPlayed == 0){
player.play()
Data.backgroundMenuPlayed = 1
}
}
游戏风格:
文件Sfx.swift
import AVFoundation
public let sfx = Sfx.shared
public final class Sfx: NSObject {
static let shared = Sfx()
var apCheer: AVAudioPlayer? = nil
// etc
private override init() {
guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else { print("Sfx woe"); return }
do { apCheer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s)) } catch { print("Sfx woe"); return }
// etc
}
func cheer() { apCheer?.play() }
func plonk() { apPlonk?.play() }
func crack() { apCrack?.play() }
// etc
}
只要吃一个……
var apCheer: AVAudioPlayer? = nil
对于你的每一个音频刺。所以你可能有5 20 10等等。
对于每一个,简单地复制/粘贴两行初始化代码:
guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else { return print("Sfx woe") }
do { apCheer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s)) } catch { return print("Sfx woe") }
然后,在任何地方,任何代码,任何文件,你都可以:
sfx.cheer()
sfx.crack()