Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ npm install react-audio-voice-recorder
yarn add react-audio-voice-recorder
```

## Version 2.3.0
- Added support to NextJs 15

## Migrating from v1 → v2
### Breaking changes
- In v2 the `AudioRecorder` prop `downloadFileExtension` no longer supports `mp3` and `wav` without the website using this package being [cross-origin isolated](https://web.dev/cross-origin-isolation-guide/). This change was made in order to fix [issue #54](https://github.com/samhirtarif/react-audio-recorder/issues/54) in v1.2.1
Expand Down Expand Up @@ -88,6 +91,7 @@ The hook returns the following:
| :------------ |:---------------|
| **`startRecording`** | Invoking this method starts the recording. Sets `isRecording` to `true` |
| **`stopRecording`** | Invoking this method stops the recording in progress and the resulting audio is made available in `recordingBlob`. Sets `isRecording` to `false` |
| **`cancelRecording`** | Invoking this method cancels the recording in progress and discard audio. Sets `isRecording` to `false` |
| **`togglePauseResume`** | Invoking this method would pause the recording if it is currently running or resume if it is paused. Toggles the value `isPaused` |
| **`recordingBlob`** | This is the recording blob that is created after `stopRecording` has been called |
| **`isRecording`** | A boolean value that represents whether a recording is currently in progress |
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "react-audio-voice-recorder",
"name": "@rafaelmarreca/react-audio-voice-recorder",
"private": false,
"version": "2.2.0",
"version": "0.1.0",
"type": "module",
"license": "MIT",
"author": "Samhir Tarif",
"author": "Rafael Marreca",
"repository": {
"type": "git",
"url": "https://github.com/samhirtarif/react-audio-recorder.git"
"url": "https://github.com/rafael145a/react-audio-recorder.git"
},
"keywords": [
"react",
Expand Down
16 changes: 11 additions & 5 deletions src/components/AudioRecordingComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@ import resumeSVG from "../icons/play.svg";
import saveSVG from "../icons/save.svg";
import discardSVG from "../icons/stop.svg";
import "../styles/audio-recorder.css";

const LiveAudioVisualizer = React.lazy(async () => {
const { LiveAudioVisualizer } = await import("react-audio-visualize");
return { default: LiveAudioVisualizer };
});
import LiveAudioVisualizer from "./ReactAudioVisualizerWrapper";

/**
* Usage: https://github.com/samhirtarif/react-audio-recorder#audiorecorder-component
Expand Down Expand Up @@ -43,9 +39,11 @@ const AudioRecorder: (props: Props) => ReactElement = ({
startRecording,
stopRecording,
togglePauseResume,
cancelRecording,
recordingBlob,
isRecording,
isPaused,
isCancelled,
recordingTime,
mediaRecorder,
} =
Expand All @@ -62,6 +60,9 @@ const AudioRecorder: (props: Props) => ReactElement = ({
const stopAudioRecorder: (save?: boolean) => void = (
save: boolean = true
) => {
if (!save) {
cancelRecording();
}
setShouldSave(save);
stopRecording();
};
Expand Down Expand Up @@ -116,6 +117,7 @@ const AudioRecorder: (props: Props) => ReactElement = ({

useEffect(() => {
if (
!isCancelled &&
(shouldSave || recorderControls) &&
recordingBlob != null &&
onRecordingComplete != null
Expand All @@ -127,6 +129,10 @@ const AudioRecorder: (props: Props) => ReactElement = ({
}
}, [recordingBlob]);

useEffect(() => {
stopRecording();
}, [isCancelled]);

return (
<div
className={`audio-recorder ${isRecording ? "recording" : ""} ${
Expand Down
49 changes: 49 additions & 0 deletions src/components/ReactAudioVisualizerWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */

import React from "react";

// Função para carregar o componente dinamicamente
const loadVisualizer = async () => {
try {
// Tenta importar de forma segura
const module = await import("react-audio-visualize");
return module.LiveAudioVisualizer;
} catch (error) {
console.error("Error loading LiveAudioVisualizer:", error);
// Retorna um componente vazio em caso de erro
return () => null;
}
};

// Componente wrapper que carrega o visualizador sob demanda
const DynamicLiveAudioVisualizer = (props: any) => {
const [Component, setComponent] = React.useState(null);
const [loading, setLoading] = React.useState(true);

React.useEffect(() => {
let isMounted = true;

const load = async () => {
const VisualizerComponent = await loadVisualizer();
if (isMounted) {
// @ts-expect-error
setComponent(() => VisualizerComponent);
setLoading(false);
}
};

void load();

return () => {
isMounted = false;
};
}, []);

if (loading || !Component) {
return null;
}
// @ts-expect-error
return <Component {...props} />;
};

export default DynamicLiveAudioVisualizer;
15 changes: 14 additions & 1 deletion src/hooks/useAudioRecorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ export interface recorderControls {
startRecording: () => void;
stopRecording: () => void;
togglePauseResume: () => void;
cancelRecording: () => void;
recordingBlob?: Blob;
isRecording: boolean;
isPaused: boolean;
isCancelled: boolean;
recordingTime: number;
mediaRecorder?: MediaRecorder;
}
Expand Down Expand Up @@ -49,6 +51,7 @@ const useAudioRecorder: (
) => {
const [isRecording, setIsRecording] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [isCancelled, setIsCancelled] = useState(false);
const [recordingTime, setRecordingTime] = useState(0);
const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder>();
const [timerInterval, setTimerInterval] = useState<NodeJS.Timer>();
Expand All @@ -71,7 +74,7 @@ const useAudioRecorder: (
*/
const startRecording: () => void = useCallback(() => {
if (timerInterval != null) return;

setIsCancelled(false);
navigator.mediaDevices
.getUserMedia({ audio: audioTrackConstraints ?? true })
.then((stream) => {
Expand Down Expand Up @@ -136,13 +139,23 @@ const useAudioRecorder: (
}
}, [mediaRecorder, setIsPaused, _startTimer, _stopTimer]);

/**
* Calling this method would cancel the recording and discard
*/
const cancelRecording: () => void = useCallback(() => {
setIsCancelled(true);
setIsRecording(false);
}, []);

return {
startRecording,
stopRecording,
togglePauseResume,
cancelRecording,
recordingBlob,
isRecording,
isPaused,
isCancelled,
recordingTime,
mediaRecorder,
};
Expand Down
19 changes: 15 additions & 4 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";
import ReactDOM from "react-dom/client";
import AudioRecorder from "./components/AudioRecordingComponent";
import useAudioRecorder from "./hooks/useAudioRecorder";

const addAudioElement = (blob: Blob) => {
const url = URL.createObjectURL(blob);
Expand All @@ -10,8 +11,10 @@ const addAudioElement = (blob: Blob) => {
document.body.appendChild(audio);
};

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
function AudioRecorderComp() {
const { isRecording, stopRecording, cancelRecording, ...recordControls } = useAudioRecorder()

return (<>
<AudioRecorder
onRecordingComplete={(blob) => addAudioElement(blob)}
// audioTrackConstraints={{
Expand All @@ -20,8 +23,16 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
// }}
onNotAllowedOrFound={(err) => console.table(err)}
showVisualizer={true}
downloadOnSavePress
downloadFileExtension="mp3"
recorderControls={{ isRecording, stopRecording, cancelRecording, ...recordControls}}
/>
<button onClick={stopRecording}>Save</button>
<button onClick={cancelRecording}>Cancel</button>
</>
)
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<AudioRecorderComp />
</React.StrictMode>
);