Experiencing Only Noise During Playback of PCM Audio Data Streamed via WebSocket in React Native and Swift

I’m developing a React Native application that receives PCM audio data over WebSocket, decodes it from a base64 string, and attempts to play it in real-time using an AVAudioEngine setup in Swift. Despite confirming that the audio data is correctly received by writing to file and playing it in Audacity, the playback in my app is only noise. I can’t identify the cause.

JavaScript Code:

const handleAudioOutput = async (event) => {
    const arrayBuffer = event.data;
    const base64Data = Buffer.from(arrayBuffer).toString('base64');
    // await RNFS.appendFile(`${RNFS.DocumentDirectoryPath}/audioData.raw`, base64Data, 'base64');
    audioPlayer.current.playAudioData(base64Data);
};

useEffect(() => {
    audioOutputWs.current = new WebSocket(audioOutputUrl);
    audioOutputWs.current.onopen = () => console.log("Audio output ws open");
    audioOutputWs.current.binaryType = 'arraybuffer';
    audioOutputWs.current.onmessage = handleAudioOutput;
  }, []);

On the swift side, we are buffering the received audio and playing from the buffer in a different thread.

Swift side Implementation:

import Foundation
import AVFoundation

@objc(AudioPlayer)
class AudioPlayer: NSObject {
  
  private var audioEngine: AVAudioEngine
  private var audioPlayerNode: AVAudioPlayerNode
  private var audioFormat: AVAudioFormat
  private var audioQueue: [Data]
  private let queueLock = NSLock()
  private var isProcessing = false
  
  override init() {
    audioEngine = AVAudioEngine()
    audioPlayerNode = AVAudioPlayerNode()
    
    // Try using a common sample rate and format
    let sampleRate: Double = 24000.0
    let channelCount: AVAudioChannelCount = 1
    let commonFormat: AVAudioCommonFormat = .pcmFormatInt16
      
    guard let format = AVAudioFormat(commonFormat: commonFormat, sampleRate: sampleRate, channels: channelCount, interleaved: false) else {
        fatalError("Failed to create AVAudioFormat")
    }

    
    audioFormat = format
    audioQueue = []
    
    super.init()
    
     audioEngine.attach(audioPlayerNode)
    // If I did format: audioFormat the constructor would crash So I found the below solution from some corner of the internet.
    audioEngine.connect(audioPlayerNode, to: audioEngine.outputNode, format: AVAudioFormat.init(standardFormatWithSampleRate: 24000.0, channels: 1)!)

     do {
       try audioEngine.start()
     } catch {
       print("Failed to start AVAudioEngine: (error)")
     }
    
     DispatchQueue.global(qos: .background).async {
       self.processAudioQueue()
     }
  }

  @objc(multiply:withB:withResolver:withRejecter:)
  func multiply(a: Float, b: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
    resolve(a * b)
  }

  @objc(add:withB:withResolver:withRejecter:)
  func add(a: Float, b: Float, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
    resolve(a + b)
  }

  @objc(playAudioData:withResolver:withRejecter:)
  func playAudioData(base64String: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
        guard let data = Data(base64Encoded: base64String) else {
            reject("error", "Invalid base64 string", nil)
            return
        }

        queueLock.lock()
        audioQueue.append(data)
        queueLock.unlock()
        
        resolve(true) // Immediately resolve to not block the JS thread
  }

  private func processAudioQueue() {
      isProcessing = true
      while isProcessing {
          queueLock.lock()
          if !audioQueue.isEmpty {
              let data: Data = audioQueue.removeFirst()
              queueLock.unlock()
              
              let frameCount = AVAudioFrameCount(data.count / MemoryLayout<Int16>.size)
              guard let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: frameCount) else {
                  continue
              }
              audioBuffer.frameLength = frameCount
              
              // Safe memory transfer using buffer pointers
              data.withUnsafeBytes { rawBufferPointer in
                  guard let bufferPointer = rawBufferPointer.bindMemory(to: Int16.self).baseAddress else {
                      return
                  }
                  guard let channelData = audioBuffer.int16ChannelData else {
                      return
                  }
                  
                  for frameIndex in 0..<Int(frameCount) {
                      channelData[0][frameIndex] = bufferPointer[frameIndex]
                  }
              }

              audioPlayerNode.scheduleBuffer(audioBuffer, at: nil, options: [], completionHandler: nil)
              
              if !audioPlayerNode.isPlaying {
                  audioPlayerNode.play()
              }
          } else {
              queueLock.unlock()
              usleep(10000) // Sleep for 10ms to avoid busy waiting
          }
      }
  }


  deinit {
    isProcessing = false
  }
}

What I’ve Tried:

  1. Tried both Int16 and Float32
  2. Tried both interleaved and non-interleaved settings.
  3. Verified by writing it down to file and playing it. (Play perfectly)
  4. Just to verify more I tried to play the stream from same websocket over a python script using pyaudio and it played well here is the code for that:
async def _audio_player(self):
    """Asynchronously plays audio from the data received from ws."""
    self.stream_out = self.audio.open(
        format=8,
        channels=1,
        rate=24000,
        output=True,
    )
    while True:
        audio_bytes = await self.listen_to_audio_output()
        self.stream_out.write(audio_bytes)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật