我试图在我的Swift应用程序中播放一个简短的声音。 我想要播放的声音:
除此之外,我想:
到目前为止,这就是我所拥有的:
import AVFoundation
class SoundPlayer {
// Singleton
class var sharedInstance : SoundPlayer {
struct Static {
static let instance : SoundPlayer = SoundPlayer()
}
return Static.instance
}
// Properties
var error:NSError?
var audioPlayer = AVAudioPlayer()
let soundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "wav")!) // Working
//let soundURL = NSURL(string:"/System/Library/Audio/UISounds/sms-received1.caf") // Working
//let soundURL = NSURL(fileURLWithPath: NSBundle(identifier: "com.apple.UIKit")!.pathForResource("sms-received1", ofType: "caf")!) // Not working (crash at runtime)
init() {
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
if (error != nil) {
println("[SoundPlayer] There was an error: \(error)")
}
}
func playSound() {
if (audioPlayer.playing) {
audioPlayer.stop()
}
audioPlayer.play()
}
}
据我所知,有几种播放声音的方法。
两种最常见的方式似乎是:AVAudioPlayer
(就像我做的那样)和AudioToolbox
。
从那里开始,我问自己三个问题:
AVAudioPlayer
目前正常运作) NSURL(string:"/System/Library/Audio/UISounds/sms-received1.caf")
是检索声音的好方法吗?有没有更好/更合适的解决方案?