swift - Audiokit AKSampler 作为单独类中的 AKNode/AKPolyphonicNode
问题描述
解决方案
For the SoundEngine.swift:
import AudioKit
final class SoundEngine {
static let shared = SoundEngine()
// Create instance variables of the MySampler objects.
// I renamed them from noise1, noise2, and mySampler1, so that they are descriptive and clear about the intended sounds from each MySampler object.
var kick: MySampler
var snare: MySampler
var hiHat: MySampler
var drumMixer: AKMixer
init() {
// Instantiate MySampler objects
kick = MySampler()
snare = MySampler()
hiHat = MySampler()
// These drum samples are royalty-free from Music Radar: https://www.musicradar.com/news/drums/1000-free-drum-samples
kick.loadSample(filePath: "CYCdh_K2room_Kick-08")
snare.loadSample(filePath: "CYCdh_K2room_Snr-05")
hiHat.loadSample(filePath: "CYCdh_K2room_ClHat-06")
// Initialize the AudioKit engine settings.
AKSettings.bufferLength = .medium
AKSettings.enableRouteChangeHandling = true
AKSettings.playbackWhileMuted = true
do {
try AKSettings.setSession(category: .playAndRecord, with: [.defaultToSpeaker, .allowBluetooth, .mixWithOthers])
} catch {
AKLog("Could not set session category.")
}
// Combine the samples into a mixer, so that they can be played together in a single output.
drumMixer = AKMixer(snare, kick, hiHat)
AudioKit.output = drumMixer
// Start the audio engine
try! AudioKit.start()
}
// MARK: Sample Playback Triggers
// The following functions can be triggered via the button actions from the ViewController.
internal func playKick() {
try! kick.play(noteNumber: 60, velocity: 127, channel: 0)
}
internal func playSmare() {
try! snare.play(noteNumber: 60, velocity: 127, channel: 0)
}
internal func playHiHat() {
try! hiHat.play(noteNumber: 60, velocity: 127, channel: 0)
}
}
For MySampler.swift:
import AudioKit
class MySampler: AKMIDISampler {
internal func loadSample(filePath: String) {
do {
try self.loadWav(Constants.sampleDirectoryPath + filePath)
// This will interpolate a string variable path like this: "Sounds/CYCdh_K2room_Kick-08"
} catch {
print("Could not locate the wav file.")
}
}
}
I also added a Constant, so that you could just provide the audio file name, and not have to include the directory path.
Constants.swift:
struct Constants {
static let sampleDirectoryPath = "Sounds/"
}
I created a GitHub project for your reference:
推荐阅读
- selenium - 如何在特征中创建数据并将其作为参数传递给 Cucumber 中的下一个特征
- c# - 表达式树 - 参数未从 lambda 函数参数映射到表达式参数
- sql - 使用窗口函数和过滤PostgreSQL按时间条件计算移动总和/计数
- kubernetes - 我想要文件中的 Prometheus 指标而不是 prometheus UI
- typo3 - 如何在 newsletter_subscribe 扩展中添加邮件模板?
- c# - Excel 导出自动测试
- python - 如何将yaml文件路径传递给不同的模块并基于模块加载配置
- android - 使用 Glide Android OS 4(棒棒糖前版本)在 Imageview 中加载 https url
- sql - Access 2016 仅在字段包含不同文本的情况下返回第一条记录
- python - Python中的优化问题——比如Goal Seek