Swift 播放短音的最佳/正确方式
我正在尝试在我的Swift应用程序中播放一个简短的声音。 我想播放的声音:Swift 播放短音的最佳/正确方式,swift,avaudioplayer,audiotoolbox,Swift,Avaudioplayer,Audiotoolbox,我正在尝试在我的Swift应用程序中播放一个简短的声音。 我想播放的声音: 非常短(少于5秒) 是系统声音之一(例如:收到短信) 在我的应用程序的生命周期内,很可能会多次播放 可在小于声音长度的时间内发射两次(即第一次发射,第二次发射在第一次结束播放之前) 除此之外,我还想: 仅当应用程序处于活动状态且“静音模式”关闭时,才能听到声音 使手机振动(无论静音模式是开启还是关闭) 到目前为止,我的情况如下: import AVFoundation class SoundPlayer {
- 非常短(少于5秒)李>
- 是系统声音之一(例如:收到短信)李>
- 在我的应用程序的生命周期内,很可能会多次播放李>
- 可在小于声音长度的时间内发射两次(即第一次发射,第二次发射在第一次结束播放之前)李>
- 仅当应用程序处于活动状态且“静音模式”关闭时,才能听到声音李>
- 使手机振动(无论静音模式是开启还是关闭)
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(字符串:“/System/Library/Audio/UISounds/sms-received1.caf”)