import AVFoundation
class AudioSilenceSkipper {
var engine: AVAudioEngine!
var player: AVAudioPlayerNode!
var audioFile: AVAudioFile!
// Function to calculate RMS of an audio buffer
func rms(of buffer: AVAudioPCMBuffer) -> Float {
guard let floatChannelData = buffer.floatChannelData else { return 0 }
let frameLength = buffer.frameLength
let channelCount = buffer.format.channelCount
var sumOfSquares: Float = 0
for channel in 0..<Int(channelCount) {
let channelData = floatChannelData[channel]
for i in 0..<Int(frameLength) {
sumOfSquares += pow(channelData[Int(i)], 2)
}
}
let meanSquare = sumOfSquares / Float(frameLength * channelCount)
return sqrt(meanSquare)
}
// Setup audio engine and player
func setupAudioEngine(with fileURL: URL) {
do {
engine = AVAudioEngine()
player = AVAudioPlayerNode()
audioFile = try AVAudioFile(forReading: fileURL)
engine.attach(player)
let mixer = engine.mainMixerNode
engine.connect(player, to: mixer, format: audioFile.processingFormat)
try engine.start()
} catch {
print("Error setting up audio engine: \(error)")
}
}
// Process and play audio on the fly, skipping silence
func processAndPlayAudioOnTheFly(from fileURL: URL, chunkSize: AVAudioFrameCount = 1024, silenceThreshold: Float = 0.01, minSilentDuration: TimeInterval = 0.5) {
setupAudioEngine(with: fileURL)
var currentPosition: TimeInterval = 0 // Track current time in the file
var isInSilent = false
var silentStart: TimeInterval = 0
var nonSilentSegments: [(startFrame: AVAudioFramePosition, durationFrames: AVAudioFrameCount)] = [] // Store segments to play
// Function to process chunks and detect segments
func processChunks() {
while let buffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: chunkSize) {
do {
let framesRead = try audioFile.read(into: buffer, frameCount: chunkSize)
if framesRead == 0 { break } // End of file
let chunkDuration = TimeInterval(framesRead) / audioFile.fileFormat.sampleRate
let rmsValue = rms(of: buffer)
if rmsValue < silenceThreshold {
if !isInSilent {
isInSilent = true
silentStart = currentPosition
}
// This chunk is silent; check if the silent period should be skipped
currentPosition += chunkDuration
} else {
if isInSilent {
// End of silent period
let silentEnd = currentPosition
if silentEnd - silentStart >= minSilentDuration {
// Skip this silent period; do nothing
} else {
// Silent period is too short; treat as part of non-silent
nonSilentSegments.append((startFrame: AVAudioFramePosition(silentStart * audioFile.fileFormat.sampleRate), durationFrames: AVAudioFrameCount((silentEnd - silentStart) * audioFile.fileFormat.sampleRate)))
}
isInSilent = false
}
// Add this non-silent chunk to the segment
let startOfChunk = currentPosition
nonSilentSegments.append((startFrame: AVAudioFramePosition(startOfChunk * audioFile.fileFormat.sampleRate), durationFrames: AVAudioFrameCount(chunkDuration * audioFile.fileFormat.sampleRate)))
currentPosition += chunkDuration
}
// If we have a non-silent segment, schedule it immediately
if !nonSilentSegments.isEmpty {
let lastSegment = nonSilentSegments.removeFirst() // Process one at a time
player.scheduleSegment(audioFile,
startingFrame: lastSegment.startFrame,
frameCount: lastSegment.durationFrames,
at: nil) // Schedule as soon as possible
}
} catch {
print("Error reading file: \(error)")
break
}
}
// After processing, if there are any remaining segments, schedule them
for segment in nonSilentSegments {
player.scheduleSegment(audioFile,
startingFrame: segment.startFrame,
frameCount: segment.durationFrames,
at: nil)
}
player.play() // Start playback if not already playing
}
// Run processing on a background thread to avoid blocking the main thread
DispatchQueue.global(qos: .userInitiated).async {
processChunks()
}
// Ensure playback starts
if !player.isPlaying {
player.play()
}
}
}
// Example usage
let audioFileURL = Bundle.main.url(forResource: "yourAudioFile", withExtension: "m4a")! // Replace with your audio file URL
let skipper = AudioSilenceSkipper()
skipper.processAndPlayAudioOnTheFly(from: audioFileURL)
This implementation processes the audio incrementally, making it more "on the fly" than the original version. If this doesn't fully meet your needs (e.g., for actual streaming), let me know more details for further refinement!