Skip to content

How to precisely sync AudioBufferSourceNode.start() with AudioRecorder.start()? #812

@RemyNtshaykolo

Description

@RemyNtshaykolo

Hi,

I’m using react-native-audio-api and I’d like to know the best way to:

  • Play an AudioBufferSourceNode
  • Record the microphone with AudioRecorder
  • Start recording exactly when the buffer starts playing (same time reference)

Here is a very simplified example. The bufferSourceNode is passed in props:

import { AudioContext, AudioManager, AudioRecorder } from "react-native-audio-api";

type StartProps = {
  audioContext: AudioContext;
  bufferSourceNode: AudioBufferSourceNode;
};

let recorder: AudioRecorder | null = null;
let recordingStarted = false;

export async function start({ audioContext, bufferSourceNode }: StartProps) {
  AudioManager.setAudioSessionOptions({
    iosCategory: "playAndRecord",
    iosMode: "spokenAudio",
    iosOptions: ["defaultToSpeaker", "allowBluetoothA2DP"],
  });

  recorder = new AudioRecorder({
    sampleRate: 44100,
    bufferLengthInSamples: 44100 * 40,
  });

  const adapter = audioContext.createRecorderAdapter();
  adapter.connect(audioContext.destination);

  bufferSourceNode.onPositionChanged = (time) => {
    if (!recordingStarted && recorder) {
      recorder.start();
      recordingStarted = true;
      console.log("Recorder started at time", time.value);
    }
  };

  bufferSourceNode.onPositionChangedInterval = 1;

  bufferSourceNode.connect(audioContext.destination);

  await audioContext.resume();

  bufferSourceNode.start();
}

This works, but using onPositionChanged looks more like a workaround than a real sync mechanism.

Do you have any best practice ?

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions