一個簡單的網路音訊錄製庫,具有 MP3 編碼(使用 lamejs)和可選的串流/分塊輸出。由 Vocaroo 製作,快速、簡單的線上錄音器!
現在包括 vanilla-js 版本和易於使用的反應鉤子和元件!
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 >
) ;
}
若要執行 ./examples/ 目錄中的內建範例,請從專案根目錄啟動開發伺服器,然後導覽至它們。
或開始開發:
yarn install
yarn start
……或 npm 等價物是什麼。
yarn add simple - audio - recorder
import AudioRecorder from "simple-audio-recorder" ;
或者,只需使用腳本標籤:
< script type = "text/javascript" src = "audiorecorder.js" > < / script >
此外,您必須確保將 Web Worker 檔案「mp3worker.js」與您的應用程式一起分發。
// 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 ( ) ;
想要接收產生的編碼資料塊嗎?對於將串流上傳到遠端伺服器很有用。
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?
錯誤處理可以透過 Promise 和捕獲錯誤來完成,也可以透過 onerror 事件處理程序(如果已設定)來完成。
這些是透過 error.name 屬性命名的
請參閱反應鉤子和組件範例以取得使用的工作範例。
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}
。這是一個非常簡單的狀態機元件,根據目前記錄器狀態顯示不同的視圖元件。
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
函數。stop
和pause
按鈕。與其將workerUrl傳遞給useSimpleAudioRecorder
,不如在應用程式開頭的某個位置呼叫此函數以盡快預先載入worker。
可能的記錄器狀態的枚舉。由 SimpleAudioRecorder 元件使用。
RecorderStates = {
INITIAL ,
STARTING ,
RECORDING ,
PAUSED ,
ENCODING ,
COMPLETE ,
ERROR ,
COUNTDOWN
}
Simple Audio Recorder 使用 AudioWorkletNode 來提取音訊資料(如果支援),並回退到使用舊版瀏覽器上已棄用的 ScriptProcessorNode。然而,在 iOS/Safari 上使用 AudioWorkletNode 似乎偶爾會出現一些問題。大約 45 秒後,來自麥克風的音訊資料包開始遺失,產生比預期短的錄音,並出現斷斷續續和故障。因此目前,已棄用的 ScriptProcessorNode 將始終在 iOS/Safari 上使用。
AFAIK 這是一個未解決的問題,可能與 Safari 的 AudioWorklets 實作有關,並且沒有給它們足夠的 CPU 優先權。這些問題僅出現在某些裝置上。奇怪的是,在其他平台上的 Chrome 上使用舊的 ScriptProcessorNode 時也遇到了類似的問題。
Chrome 在 iOS 上也好不到哪裡去,因為他們被迫在後台使用 Safari(不知何故,這感覺相當熟悉)。
SimpleAudioRecorder 大部分是 MIT 授權的,但工作程式可能是 LGPL,因為它使用 lamejs。