В реальном времени обработка звука iOSIOS

Программируем под IOS
Ответить
Anonymous
 В реальном времени обработка звука iOS

Сообщение Anonymous »

Я пытаюсь получить звук от микрофона, обработать звук с некоторой функцией, а затем вывозить обработанное звук на динамики.
Мне нужно иметь возможность обрабатывать буферы из 1024 образцов. Но сейчас я получаю только прерывистый звук. Есть лучший способ обработать звук, а затем использовать установку для обработки в реальном времени? private func setupAudioEngine() {
do {
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
try audioSession.setActive(true)
} catch {
errorMessage = "Failed to set up audio session: \(error.localizedDescription)"
print(errorMessage ?? "")
return
}

// Get the input format
let inputNode = audioEngine.inputNode
let inputFormat = inputNode.outputFormat(forBus: 0)

// Attach nodes
audioEngine.attach(mixerNode)
audioEngine.attach(playerNode)

// Set mixer format to match input
mixerNode.outputFormat(forBus: 0)

// Connect input to mixer
audioEngine.connect(inputNode, to: mixerNode, format: nil)

// Connect mixer to output
audioEngine.connect(mixerNode, to: audioEngine.mainMixerNode, format: nil)

// Connect player to mixer (not directly to output)
audioEngine.connect(playerNode, to: audioEngine.outputNode, format: nil)

let format = AVAudioFormat(
standardFormatWithSampleRate: inputFormat.sampleRate,
channels: 2
)

// Install tap on mixer node to process audio
inputNode.installTap(onBus: 0, bufferSize: 1024, format: format) { [weak self] (buffer, audioTime) in
self!.scheduleProcessedBuffer(buffer)
}

// Prepare the engine before starting
audioEngine.prepare()
}

private func scheduleProcessedBuffer(_ buffer: AVAudioPCMBuffer) {
if playerNode.isPlaying {
playerNode.scheduleBuffer(buffer, at: nil, options: .interrupts) {
// Optional: Callback when buffer finishes playing
}
}
}
< /code>
Редактировать:
Я получил этот код, который работает в реальном времени (аудиосинка к аудиозурсу), единственная проблема заключается в том, что мне нужны буферы с 1024 образцами, и я не могу обеспечить соблюдение размера буфера. < /p>
import SwiftUI
import AVFoundation
import Combine

class CircularAudioFrameQueue {
private var queue: [AVAudioPCMBuffer]
private var headIndex = 0
private var tailIndex = 0
private let maxSize: Int
private let format: AVAudioFormat

init(format: AVAudioFormat, size: Int = 10) {
self.maxSize = size
self.format = format
self.queue = (0.. AVAudioPCMBuffer? {
guard tailIndex != headIndex else { return nil } // Empty queue check
let buffer = queue[tailIndex]
tailIndex = (tailIndex + 1) % maxSize
return buffer
}
}

class AudioRecorderManager: NSObject, ObservableObject {
private var audioEngine = AVAudioEngine()
private var noiseCanceller: ONNXNoiseCanceller?
private var frameQueue: CircularAudioFrameQueue?

@Published var isRecording = false
@Published var errorMessage: String?

override init() {
super.init()

// Initialize noise cancellation model
noiseCanceller = ONNXNoiseCanceller()

setupAudioEngine()
}

private func setupAudioEngine() {
do {
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
try audioSession.setActive(true)
} catch {
errorMessage = "Failed to set up audio session: \(error.localizedDescription)"
print(errorMessage ?? "")
return
}

// Get the input format
let inputNode = audioEngine.inputNode
let inputFormat = inputNode.outputFormat(forBus: 0)

// Create a consistent format for processing
guard let processingFormat = AVAudioFormat(
standardFormatWithSampleRate: 44100,
channels: 2
)else {
errorMessage = "Failed to create audio format"
print(errorMessage ?? "")
return
}
frameQueue = CircularAudioFrameQueue(format:processingFormat)

// Create a sink node for low-latency processing
let sinkNode = AVAudioSinkNode { [weak self] (timestamp, frameCount, audioBufferList) -> OSStatus in
guard let self = self else { return noErr }

// Get buffer pointer for direct processing
let ablPointer = UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: audioBufferList))
// Create a temporary buffer to hold input for noise cancellation
let pcmBuffer = AVAudioPCMBuffer(pcmFormat: processingFormat, frameCapacity: frameCount)!
pcmBuffer.frameLength = frameCount

// Copy data from audioBufferList to pcmBuffer for noise cancellation processing
for bufferIndex in 0..

Подробнее здесь: https://stackoverflow.com/questions/795 ... essing-ios
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»