如何使用Swift在iOS中为不同的通知响应播放单独的音频



我有一个场景,我想使用AVAudioPlayer为不同的通知响应播放不同的音频。

例如,当通知响应是yes时,我想播放audio1,类似地,对于failaudio2。我的代码如下,

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
//Presenting audioController from here
}

audioController.swift

override func viewDidLoad() {
super.viewDidLoad()
var player:AVAudioPlayer = AVAudioPlayer()
if notificationResponse == "yes" {
audioPath =  NSBundle.mainBundle().pathForResource("audio1", ofType: "mp3")
} else if notificationResponse == "no" {
audioPath = NSBundle.mainBundle().pathForResource("audio2", ofType: "mp3")
}
player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
player.numberOfLoops = -1
player.play()
}

问题是,当两个通知同时到达时,视图控制器会显示两次,并且两个音频都在播放。

当收到新的通知时,如何停止播放旧的音频?

playervar作为audioController.swift的属性,然后在AppDelegate中使audioContrler.swift类的对象为全局对象,然后为

如果audioControlle.swift类的对象已经出现,则在didReceiveRemoteNotification中出现之前,添加一个检查,因为该检查presentedViewController在哪个实例上是nil或不是nil。

如果已经显示,则停止播放器并更改播放器的audioPath,而不再次显示audioController。

var audioC : audioController // Its you global var in AppDelegate
//Use this code after adding a check the audioC is already presented or not in didReceiveRemoteNotification
audioC.player.stop() // Stop previous running audio
audioC.player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: newAudioPath!)) // newAudioPath will be your new audio files path
audioC.player.play() // Play the new audio.

最新更新