gpt4 book ai didi

swift 2 : AVAudioPlayers to play multiple sounds at once

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:06 25 4
gpt4 key购买 nike

嘿嘿

我一直在四处寻找,试图找到解决这个问题的方法,但基本上还没有解决这个问题。

我迫切需要一种方法来随时实例化和播放声音,而不会切断任何其他声音。我知道 AVAudioPlayer 一次只能播放一种声音,所以我想弄清楚如何制作一个动态的 AVAudioPlayer 数组,我可以在需要播放声音的任何时候添加它。我从本网站上的不同答案获得的当前代码是这样的:

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)
}


}

}

关于 swift 2 : AVAudioPlayers to play multiple sounds at once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37033036/

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