一个简单的网络音频录制库,具有 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。