大佬教程收集整理的这篇文章主要介绍了Swift 2: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) } }
遗憾的是,这不起作用.它播放声音,但停止播放任何其他声音.
基本上,我只需要一个与Swift 2同步的代码片段,这样我就可以播放声音,而不会删除正在播放的任何其他声音.即使两次声音效果相同.
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) } } }
以上是大佬教程为你收集整理的Swift 2:AVAudioPlayers一次播放多个声音全部内容,希望文章能够帮你解决Swift 2:AVAudioPlayers一次播放多个声音所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。