gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:21:51 24 4
gpt4 key购买 nike

我有一个场景,我想使用 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()
}

问题是,当两个通知同时到达时, View Controller 会呈现两次并且两个音频都会播放。

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

最佳答案

player var作为audioController.swift的属性,然后在AppDelegate中将audioController.swift类的对象设置为全局

添加一个检查,检查audioController.swift类的对象是否已经存在,在didReceiveRemoteNotification中呈现之前,检查您正在呈现它的实例上的presentedViewController是否为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.

关于ios - 如何使用 Swift 在 iOS 中为不同的通知响应播放单独的音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37701121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com