嘿.嘿
我一直在寻找,试图找到解决这个问题的方法,但基本上没有解决方案.
我迫切需要一种方法来实例化并随时播放声音,而不会切断任何其他声音.我知道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同步的代码片段,这样我就可以播放声音,而不会删除正在播放的任何其他声音.即使两次声音效果相同.
解决方法
这个问题听起来更像是你对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) } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。