Pustaka rekaman audio web sederhana dengan pengkodean ke MP3 (menggunakan lamejs) dan streaming opsional/output terpotong. Dibuat oleh Vocaroo, perekam suara online yang cepat dan mudah!
Sekarang termasuk versi vanilla-js dan react hook serta komponen yang mudah digunakan!
import AudioRecorder from "simple-audio-recorder" ;
AudioRecorder . preload ( "mp3worker.js" ) ;
let recorder = new AudioRecorder ( ) ;
recorder . start ( ) . then ( ( ) => {
console . log ( "Recording started..." ) ;
} ) . catch ( error => {
console . log ( error ) ;
} ) ;
recorder . stop ( ) . then ( mp3Blob => {
console . log ( "Recording stopped..." ) ;
const newAudio = document . createElement ( "audio" ) ;
newAudio . src = URL . createObjectURL ( mp3Blob ) ;
newAudio . controls = true ;
document . body . append ( newAudio ) ;
} ) . catch ( error => {
console . log ( error ) ;
} ) ;
import { SimpleAudioRecorder , useSimpleAudioRecorder } from "simple-audio-recorder/react" ;
export default function App ( ) {
const recorder = useSimpleAudioRecorder ( { workerUrl : "mp3worker.js" } ) ;
const viewInitial = < button onClick = { recorder . start } > start recording < / button > ;
const viewRecording = < button onClick = { recorder . stop } > stop recording < / button > ;
const viewError = ( < > { viewInitial } < div > Error occurred! { recorder . errorStr } < / div > < / > ) ;
return (
< div >
< SimpleAudioRecorder
{ ... recorder . getProps ( ) }
viewInitial = { viewInitial }
viewRecording = { viewRecording }
viewError = { viewError } / >
{ recorder . mp3Urls . map ( url =>
< audio key = { url } src = { url } controls / >
) }
< / div >
) ;
}
Untuk menjalankan contoh bawaan di direktori ./examples/, mulai server dev dari root proyek, lalu navigasikan ke sana.
Atau mulai berkembang dengan:
yarn install
yarn start
...atau apa pun yang setara dengan npm.
yarn add simple - audio - recorder
import AudioRecorder from "simple-audio-recorder" ;
Alternatifnya, cukup gunakan tag skrip:
< script type = "text/javascript" src = "audiorecorder.js" > < / script >
Selain itu, Anda harus memastikan bahwa Anda mendistribusikan file pekerja web "mp3worker.js" bersama dengan aplikasi Anda.
// This is a static method.
// You should preload the worker immediately on page load to enable recording to start quickly
AudioRecorder . preload ( "./mp3worker.js" ) ;
let recorder = new AudioRecorder ( {
recordingGain : 1 , // Initial recording volume
encoderBitRate : 96 , // MP3 encoding bit rate
streaming : false , // Data will be returned in chunks (ondataavailable callback) as it is encoded,
// rather than at the end as one large blob
streamBufferSize : 50000 , // Size of encoded mp3 data chunks returned by ondataavailable, if streaming is enabled
constraints : { // Optional audio constraints, see https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
channelCount : 1 , // Set to 2 to hint for stereo if it's available, or leave as 1 to force mono at all times
autoGainControl : true ,
echoCancellation : true ,
noiseSuppression : true
} ,
// Used for debugging only. Force using the older script processor instead of AudioWorklet.
// forceScriptProcessor : true
} ) ;
recorder . start ( ) . then ( ( ) => {
console . log ( "Recording started..." ) ;
} ) . catch ( error => {
console . log ( error ) ;
} ) ;
recorder . stop ( ) . then ( mp3Blob => {
// Do something with the mp3 Blob!
} ) . catch ( error => {
console . log ( error ) ;
} ) ;
recorder . onstart = ( ) => {
console . log ( "Recording started..." ) ;
} ;
recorder . onstop = ( mp3Blob ) => {
// Do something with the mp3 Blob!
// When using onstop, mp3Blob could in rare cases be null if nothing was recorded
// (with the Promise API, that would be a stop() promise rejection)
} ;
recorder . onerror = ( error ) => {
console . log ( error ) ;
} ;
// if onerror is set, start and stop won't return a promise
recorder . start ( ) ;
// later...
recorder . stop ( ) ;
Ingin menerima potongan data yang dikodekan saat diproduksi? Berguna untuk streaming upload ke server jauh.
let recorder = new AudioRecorder ( {
streaming : true ,
streamBufferSize : 50000
} ) ;
let audioChunks = [ ] ;
recorder . ondataavailable = ( data ) => {
// 50 KB of MP3 data received!
audioChunks . push ( data ) ;
} ;
recorder . start ( ) ;
// No mp3Blob will be received either with the promise API or via recorder.onstop if streaming is enabled.
recorder . stop ( ) . then ( ( ) => {
// ...do something with all the chunks that were received by ondataavailable
let mp3Blob = new Blob ( audioChunks , { type : "audio/mpeg" } ) ;
} ) ;
recorder . start ( paused = false ) ; // Supports starting in paused mode
recorder . pause ( ) ;
recorder . resume ( ) ;
recorder . setRecordingGain ( gain ) ; // Change the volume while recording is in progress (0.0 to 1.0)
recorder . time ; // Access the current recorded duration in milliseconds. Time pauses when recording is paused.
// Get the amount of data remaining to be encoded
// Will only be much above zero on very slow systems as mp3 encoding is quite fast.
// A large value indicates there might be a delay between calling stop() and getting the mp3Blob
recorder . getEncodingQueueSize ( ) ;
AudioRecorder . isRecordingSupported ( ) ; // Static method. Does this browser support getUserMedia?
Penanganan kesalahan dapat dilakukan baik melalui janji dan menangkap kesalahan, atau melalui event handler onerror jika sudah diatur.
Ini diberi nama melalui properti error.name
Silakan lihat contoh react hook dan komponen untuk contoh penggunaan yang berfungsi.
import {
useSimpleAudioRecorder ,
SimpleAudioRecorder ,
preloadWorker ,
RecorderStates
} from "simple-audio-recorder/react"
const {
error , // Any current error object, or null
errorStr , // Error object as string, or null
time , // Current recorded time in milliseconds
countdownTimeLeft , // Time left of the countdown before recording will start, if one was set
mp3Blobs , // List of all recordings as a blob
mp3Urls , // List of all recordings as URLs (created with URL.createObjectURL)
mp3Blob , // Single most recent recording blob
mp3Url , // Single most recent recording URL
start , stop , pause , resume , // Recording functions
recorderState , // Current state of recorder (see RecorderStates)
getProps // Function to get the props that can be passed to the SimpleAudioRecorder react component
} = useSimpleAudioRecorder ( {
workerUrl , onDataAvailable , onComplete , onError , options , cleanup = false , timeUpdateStep = 111 , countdown = 0
} )
{mp3Blob, mp3Url}
saat perekaman dan pengkodean selesai.Ini adalah komponen mesin status yang sangat sederhana yang menampilkan komponen tampilan berbeda bergantung pada status perekam saat ini.
SimpleAudioRecorder ( {
// As returned by useSimpleAudioRecorder
recorderState ,
// The components to display in each of the states.
// Only viewInitial and viewRecording are absolutely required.
viewInitial , viewStarting , viewCountdown , viewRecording , viewPaused , viewEncoding , viewComplete , viewError
} )
start
dari useSimpleAudioRecorder.stop
dan pause
. Daripada meneruskan pekerjaUrl ke useSimpleAudioRecorder
, lebih baik memanggil fungsi ini di suatu tempat di awal aplikasi Anda untuk melakukan pramuat pekerja sesegera mungkin.
Pencacahan kemungkinan status perekam. Digunakan oleh komponen SimpleAudioRecorder.
RecorderStates = {
INITIAL ,
STARTING ,
RECORDING ,
PAUSED ,
ENCODING ,
COMPLETE ,
ERROR ,
COUNTDOWN
}
Perekam Audio Sederhana menggunakan AudioWorkletNode untuk mengekstrak data audio, jika didukung, dan kembali menggunakan ScriptProcessorNode yang tidak digunakan lagi di browser lama. Namun, tampaknya ada beberapa masalah sesekali saat menggunakan AudioWorkletNode di iOS/Safari. Setelah sekitar 45 detik, paket audio dari mikrofon mulai terputus, sehingga menghasilkan rekaman yang lebih pendek dari yang diharapkan disertai gangguan dan gangguan. Jadi saat ini, ScriptProcessorNode yang tidak digunakan lagi akan selalu digunakan di iOS/Safari.
AFAIK ini adalah masalah yang belum terpecahkan, mungkin terkait dengan implementasi AudioWorklets di Safari dan tidak diberi prioritas CPU yang cukup. Masalah ini hanya muncul pada beberapa perangkat. Anehnya, gangguan serupa juga dialami saat menggunakan ScriptProcessorNode lama di Chrome pada platform lain.
Chrome juga tidak lebih baik di iOS karena mereka terpaksa menggunakan Safari (entah bagaimana, ini terasa familiar).
SimpleAudioRecorder sebagian besar berlisensi MIT, tetapi pekerjanya mungkin LGPL karena menggunakan lamejs.