Swift 2:AVAudioPlayers一次播放多个声音
发布时间:2020-12-14 04:46:16 所属栏目:百科 来源:网络整理
导读:嘿.嘿 我一直在寻找,试图找到解决这个问题的方法,但基本上没有解决方案. 我迫切需要一种方法来实例化并随时播放声音,而不会切断任何其他声音.我知道AVAudioPlayer一次只能播放一个声音,所以我想弄清楚如何制作AVAudioPlayers的动态数组,我可以在需要播放声音
嘿.嘿
我一直在寻找,试图找到解决这个问题的方法,但基本上没有解决方案. 我迫切需要一种方法来实例化并随时播放声音,而不会切断任何其他声音.我知道AVAudioPlayer一次只能播放一个声音,所以我想弄清楚如何制作AVAudioPlayers的动态数组,我可以在需要播放声音的任何时候添加它.我在本网站上从不同的答案得到的当前代码是: func Sound(sound: String) { do { if let bundle = NSBundle.mainBundle().pathForResource(sound,ofType: "wav") { let alertSound = NSURL(fileURLWithPath: bundle) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) try AVAudioSession.sharedInstance().setActive(true) try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound) audioPlayer.prepareToPlay() audioPlayer.play() } } catch { print(error) } } 遗憾的是,这不起作用.它播放声音,但停止播放任何其他声音. I’ve also tried the code from here,but I’m having the same problem the asker is having,and there’s no solution. 基本上,我只需要一个与Swift 2同步的代码片段,这样我就可以播放声音,而不会删除正在播放的任何其他声音.即使两次声音效果相同. 解决方法
这个问题听起来更像是你对Swift数据结构并不十分了解,但这里有一个简单的片段可以帮助你:
import UIKit import AVFoundation class ViewController: UIViewController { var arrayOfPlayers = [AVAudioPlayer]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. sound("tester") let delayTime = dispatch_time(DISPATCH_TIME_NOW,Int64(2 * Double(NSEC_PER_SEC))) dispatch_after(delayTime,dispatch_get_main_queue()) { self.sound("tester") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sound(sound: String) { do { if let bundle = NSBundle.mainBundle().pathForResource(sound,ofType: "wav") { let alertSound = NSURL(fileURLWithPath: bundle) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) try AVAudioSession.sharedInstance().setActive(true) let audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound) arrayOfPlayers.append(audioPlayer) arrayOfPlayers.last?.prepareToPlay() arrayOfPlayers.last?.play() } } catch { print(error) } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |