Skip to content

Commit 379d86d

Browse files
committed
Try to reduce crashes when using certain URL types.
1 parent ff1efec commit 379d86d

2 files changed

Lines changed: 35 additions & 15 deletions

File tree

SoundFontsFramework/SoundFontsFramework/Audio/SoundFontsAU.swift

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -188,21 +188,28 @@ extension SoundFontsAU {
188188
return
189189
}
190190

191+
let url = soundFont.fileURL
192+
let secured = url.startAccessingSecurityScopedResource()
193+
defer { if secured { url.stopAccessingSecurityScopedResource() } }
194+
195+
guard FileManager.default.fileExists(atPath: url.path) else {
196+
log.error("reloadActivePreset - soundFont file \(url.path) does not exist")
197+
return
198+
}
199+
191200
// NOTE: do this here instead of using the PresetChangeManager as we want this to run in the current thread.
192-
if FileManager.default.fileExists(atPath: soundFont.fileURL.path) {
193-
do {
194-
try sampler.loadSoundBankInstrument(
195-
at: soundFont.fileURL,
196-
program: UInt8(activePreset.program),
197-
bankMSB: UInt8(activePreset.bankMSB),
198-
bankLSB: UInt8(activePreset.bankLSB)
199-
)
200-
} catch {
201-
log.error("reloadActivePreset - failed to load sound font: \(error)")
202-
}
203-
} else {
204-
log.error("reloadActivePreset - soundFont file \(soundFont.fileURL.path) does not exist")
201+
do {
202+
sampler.reset()
203+
try sampler.loadSoundBankInstrument(
204+
at: url,
205+
program: UInt8(activePreset.program),
206+
bankMSB: UInt8(activePreset.bankMSB),
207+
bankLSB: UInt8(activePreset.bankLSB)
208+
)
209+
} catch {
210+
log.error("reloadActivePreset - failed to load sound font: \(error)")
205211
}
212+
206213
log.debug("reloadActivePreset END")
207214
}
208215

SoundFontsFramework/SoundFontsFramework/Protocols/PresetLoader.swift

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,22 @@ public protocol PresetLoader: AnyObject {
2323
extension AVAudioUnitSampler: PresetLoader {
2424

2525
public func loadAndActivatePreset(_ preset: Preset, from url: URL) -> NSError? {
26+
let secured = url.startAccessingSecurityScopedResource()
27+
defer { if secured { url.stopAccessingSecurityScopedResource() } }
28+
29+
guard FileManager.default.fileExists(atPath: url.path) else {
30+
os_log(.error, "reloadActivePreset - soundFont file %{public}s does not exist", url.path)
31+
return nil
32+
}
33+
2634
do {
27-
try loadSoundBankInstrument(at: url, program: UInt8(preset.program), bankMSB: UInt8(preset.bankMSB),
28-
bankLSB: UInt8(preset.bankLSB))
35+
reset()
36+
try loadSoundBankInstrument(
37+
at: url,
38+
program: UInt8(preset.program),
39+
bankMSB: UInt8(preset.bankMSB),
40+
bankLSB: UInt8(preset.bankLSB)
41+
)
2942
} catch let error as NSError {
3043
switch error.code {
3144
case -43: // not found

0 commit comments

Comments
 (0)