Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 播放短音的最佳/正确方式_Swift_Avaudioplayer_Audiotoolbox - Fatal编程技术网

Swift 播放短音的最佳/正确方式

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

我正在尝试在我的Swift应用程序中播放一个简短的声音。 我想播放的声音:

  • 非常短(少于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”)
      是检索声音的好方法吗?有更好/合适的解决方案吗
  • 有没有办法在发出声音的同时震动手机