Swift – AVAudioPlayer,声音无法正常播放

因为在应用程序处于活动状态时没有显示UIlocalnotification,所以我正在尝试配置UIAlertController并在它出现时播放一些声音.

我在AppDelegate中没有问题来处理通知/创建警报.我的问题涉及声音.实际上,它无法正常播放.

这是我到目前为止:

//...
class AppDelegate: UIResponder,UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // Notifications permissions
    let types: UIUserNotificationType = UIUserNotificationType.sound | UIUserNotificationType.Alert
    let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types,categories: nil)
    application.registerUserNotificationSettings(settings)

    return true
}

func application(application: UIApplication!,didReceivelocalnotification notification: UIlocalnotification!) {
    let state : UIApplicationState = application.applicationState
    var audioPlayer = AVAudioPlayer()

    if (state == UIApplicationState.Active) {
        // Create sound

        var error:NSError?
        var audioPlayer = AVAudioPlayer()

        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient,error: nil)
        AVAudioSession.sharedInstance().setActive(true,error: nil)

        let soundURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound",ofType: "wav")!)

        audioPlayer = AVAudioPlayer(contentsOfURL: soundURL,error: &error)

        if (error != nil) {
            println("There was an error: \(error)")
        } else {
            audioPlayer.preparetoPlay()
            audioPlayer.play()
        }

        // Create alert
        let alertController = UIAlertController(title: "Alert title",message: "Alert message.",preferredStyle: .Alert)

        let noAction = UIAlertAction(title: "No",style: .Cancel) { (action) in
            // ...
        }
        let yesAction = UIAlertAction(title: "Yes",style: .Default) { (action) in
            // ...
        }

        alertController.addAction(noAction)
        alertController.addAction(yesAction)

        self.window?.rootViewController?.presentViewController(alertController,animated: true,completion: nil)

    }

}

有了这个,玩家通过这一行:audioPlayer.play()
它的播放时间不到一秒钟.就像它突然被解除分配一样(?).

我试过以下两件事:

>在创建警报之前(或在显示警报之后)将AVAudioPlayer状态切换回非活动状态:AVAudioSession.sharedInstance().setActive(false,error:nil).如果我这样做,声音播放正确.但是,这种方法是一种同步(阻塞)操作,因此它会延迟其他事情(声音在声音后显示).显然不是一个好的解决方案.
>将audioPlayer属性(var audioPlayer = AVAudioPlayer())移动到类级别,就在窗口下(var window:UIWindow?).如果我这样做,声音播放正确,警报也正确显示.

我不明白为什么它会这样.我错过了什么吗?这是解决我问题的正确方法吗?

提前感谢所有能帮助我理解/解决这个问题的人.

你已经为你的问题提供了正确的解决方案,那就是#2;拥有一个类级别的audioPlayer属性.为什么会这样?
嗯,那是因为在代码中你设置了播放器,开始播放,显示弹出窗口,一切都完成后,该方法退出其范围.自动内存管理(ARC)可以在退出该变量的范围时释放任何局部变量.如果您认为声音播放是异步的(例如,它将在不阻塞主线程的情况下播放),则在音频播放器播放完声音之前退出示波器. ARC注意到audioPlayer是一个局部变量并在那时释放它,但声音尚未播放.

我希望我足够清楚,如果不是随意多问!

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...