我正在为 iOS 制作一个基本的音乐应用程序,按下音符会播放相应的声音。我正在尝试让存储在缓冲区中的多个声音以最小的延迟同时播放。但是,我每次只能播放一种声音。
我最初使用多个 AVAudioPlayer 对象设置声音,为每个播放器分配一个声音。虽然它确实同时播放多个声音,但它似乎无法同时启动两个声音(似乎它会在第一个声音启动后稍微延迟第二个声音)。此外,如果我以非常快的速度按下音符,引擎似乎无法跟上,并且在我按下后面的音符后,后面的声音就会很好地开始。
我正在尝试解决这个问题,从我所做的研究来看,使用 AVAudioEngine 播放声音似乎是最好的方法,我可以在缓冲区数组中设置声音,然后让它们播放从这些缓冲区中。
class ViewController: UIViewController
{
// Main Audio Engine and it's corresponding mixer
var audioEngine: AVAudioEngine = AVAudioEngine()
var mainMixer = AVAudioMixerNode()
// One AVAudioPlayerNode per note
var audioFilePlayer: [AVAudioPlayerNode] = Array(repeating: AVAudioPlayerNode(), count: 7)
// Array of filepaths
let noteFilePath: [String] = [
Bundle.main.path(forResource: "note1", ofType: "wav")!,
Bundle.main.path(forResource: "note2", ofType: "wav")!,
Bundle.main.path(forResource: "note3", ofType: "wav")!]
// Array to store the note URLs
var noteFileURL = [URL]()
// One audio file per …Run Code Online (Sandbox Code Playgroud)