You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AudioKit中对MIDISampler执行程序变更以切换soundfont乐器?

解决AudioKit MIDISampler加载SoundFont后无法通过Program Change切换乐器的问题

你遇到的问题核心在于**loadInstrument(url:)方法只会加载SoundFont中的单个乐器**——哪怕你的SoundFont包含多种乐器,默认也只加载第一个,所以后续发送Program Change指令时没有对应的乐器样本可以切换。

正确解决方案步骤:

  1. 改用loadSoundFont(url:)加载完整SoundFont
    这个方法会加载SoundFont文件内的所有乐器映射,让MIDISampler能识别Program Change指令对应的乐器。

    修改加载代码:

    var instrument = MIDISampler(name: "Instrument 1")
    let soundFontUrl = Bundle.main.url(forResource: "soundfont", withExtension: "sf2")!
    // 加载整个SoundFont的所有乐器
    try! instrument.loadSoundFont(url: soundFontUrl)
    
  2. 正确发送Program Change指令
    加载完整SoundFont后,再发送Program Change就能切换乐器了,直接调用MIDISampler的sendProgramChange方法即可(无需直接操作samplerUnit):

    let channel: UInt8 = 0
    let program: UInt8 = 33
    // 发送Program Change切换乐器
    instrument.sendProgramChange(program, onChannel: channel)
    // 播放音符
    instrument.play(noteNumber: 60, velocity: 80, channel: channel)
    

额外注意事项:

  • 确认SoundFont中的program编号与你指定的一致,不同SoundFont可能对GM标准编号有调整,比如部分自定义SoundFont的乐器编号并非GM标准的33对应电钢琴。
  • 如果涉及Bank切换(部分SoundFont用Bank区分乐器组),需要先发送Bank Select指令:
    let channel: UInt8 = 0
    let bankMSB: UInt8 = 0
    let bankLSB: UInt8 = 0
    let program: UInt8 = 33
    
    instrument.sendBankSelectMSB(bankMSB, onChannel: channel)
    instrument.sendBankSelectLSB(bankLSB, onChannel: channel)
    instrument.sendProgramChange(program, onChannel: channel)
    

内容的提问来源于stack exchange,提问作者AI-Guru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 17:37:03