### Record Audio: startRecord / finishRecord / cancelRecord Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Initiate recording by calling initWithRecord() to get microphone permissions, then startRecord(). Use finishRecord() to encode and save the audio (returns a Promise), or cancelRecord() to discard it. Ensure initWithRecord() is called before starting the recording process. ```javascript var amrRec = new BenzAMRRecorder(); // 第一步:初始化(绑定到用户点击事件) document.getElementById('btn-init').addEventListener('click', function () { amrRec.initWithRecord().then(function () { console.log('麦克风就绪'); }); }); // 第二步:开始录音 document.getElementById('btn-start').addEventListener('click', function () { amrRec.onStartRecord(function () { console.log('🎙 录音中...'); }); amrRec.startRecord(); console.log('是否录音中:', amrRec.isRecording()); // true }); // 第三步:结束录音并播放 document.getElementById('btn-finish').addEventListener('click', function () { amrRec.onFinishRecord(function () { console.log('录音结束,时长:' + amrRec.getDuration().toFixed(2) + ' 秒'); }); amrRec.finishRecord().then(function () { amrRec.play(); // 立即回放刚录制的音频 }); }); // 放弃录音 document.getElementById('btn-cancel').addEventListener('click', function () { amrRec.cancelRecord(); console.log('录音已取消'); }); ``` -------------------------------- ### Start Recording Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initiates the audio recording process. ```javascript amr.startRecord(); ``` -------------------------------- ### Install Benz AMR Recorder via npm Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Use npm to install the library for use in your Node.js projects. ```bash npm install benz-amr-recorder ``` -------------------------------- ### Record and start AMR recording Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initialize the recorder for recording and then start capturing audio. Initialization should ideally be tied to a user interaction. ```javascript var amrRec = new BenzAMRRecorder(); amrRec.initWithRecord().then(function() { amrRec.startRecord(); }); ``` -------------------------------- ### Play Audio Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Starts playback of the audio. If a `startTime` is provided, playback begins at that specific second. This method ignores any current pause state. ```javascript amr.play(); ``` -------------------------------- ### Playback Controls Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Methods for controlling audio playback, including starting, stopping, pausing, resuming, and seeking. ```APIDOC ## play ### Description Starts audio playback, ignoring any current pause state. Can optionally specify a start time. ### Method amr.play(startTime?: number) ### Parameters - **startTime** (number, optional) - The time in seconds from which to start playback. Accepts floating-point numbers. ``` ```APIDOC ## stop ### Description Stops the current audio playback. ### Method amr.stop() ``` ```APIDOC ## pause ### Description Pauses the current audio playback. Available since version 1.1.0. ### Method amr.pause() ``` ```APIDOC ## resume ### Description Resumes playback from a paused state. Available since version 1.1.0. ### Method amr.resume() ``` ```APIDOC ## playOrResume ### Description If the audio is paused, resumes playback. Otherwise, starts playback from the beginning. Available since version 1.1.0. ### Method amr.playOrResume() ``` ```APIDOC ## pauseOrResume ### Description Toggles the pause state of the audio. If playing, pauses it. If paused, resumes it. Available since version 1.1.0. ### Method amr.pauseOrResume() ``` ```APIDOC ## playOrPauseOrResume ### Description Provides a unified control for playback state: plays if not playing, resumes if paused, and pauses if playing. Available since version 1.1.0. ### Method amr.playOrPauseOrResume() ``` ```APIDOC ## setPosition ### Description Sets the playback position to a specified time without changing the playback state. If in a stopped state, this is equivalent to `play(time)`. Available since version 1.1.0. ### Method amr.setPosition(time: number) ### Parameters - **time** (number) - The desired playback position in seconds. Accepts floating-point numbers. ``` ```APIDOC ## getCurrentPosition ### Description Retrieves the current playback position in seconds. Available since version 1.1.0. ### Method amr.getCurrentPosition(): number ### Returns - **number** - The current playback position in seconds (floating-point). ``` ```APIDOC ## isPlaying ### Description Checks if the audio is currently playing. ### Method amr.isPlaying(): boolean ### Returns - **boolean** - `true` if playing, `false` otherwise. ``` ```APIDOC ## isPaused ### Description Checks if the audio is currently paused. Available since version 1.1.0. ### Method amr.isPaused(): boolean ### Returns - **boolean** - `true` if paused, `false` otherwise. ``` -------------------------------- ### Recording Controls Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Methods for managing audio recording, including starting, finishing, canceling, and checking recording status. ```APIDOC ## startRecord ### Description Initiates audio recording. ### Method amr.startRecord() ``` ```APIDOC ## finishRecord ### Description Stops recording and converts the recorded audio into AMR format. Returns a Promise. ### Method amr.finishRecord(): Promise ``` ```APIDOC ## cancelRecord ### Description Abandons the current recording session. ### Method amr.cancelRecord() ``` ```APIDOC ## isRecording ### Description Checks if the device is currently recording audio. ### Method amr.isRecording(): boolean ### Returns - **boolean** - `true` if recording, `false` otherwise. ``` -------------------------------- ### Basic Playback Controls for BenzAMRRecorder Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Control audio playback using `play`, `stop`, `pause`, and `resume` methods. `play` can optionally take a start time in seconds. Also demonstrates checking playback status with `isPlaying` and `isPaused`. ```javascript var amr = new BenzAMRRecorder(); amr.initWithUrl('path/to/voice.amr').then(function () { // 从头播放 document.getElementById('btn-play').onclick = function () { amr.play(); }; // 从第 3 秒开始播放 document.getElementById('btn-play-3s').onclick = function () { amr.play(3); }; // 暂停 document.getElementById('btn-pause').onclick = function () { amr.pause(); }; // 从暂停处继续 document.getElementById('btn-resume').onclick = function () { amr.resume(); }; // 停止(重置到开头) document.getElementById('btn-stop').onclick = function () { amr.stop(); }; console.log('是否正在播放:', amr.isPlaying()); // false console.log('是否已暂停:', amr.isPaused()); // false }); ``` -------------------------------- ### Record, Encode, and Download AMR Source: https://github.com/benzleung/benz-amr-recorder/blob/master/demo.html Initializes the BenzAMRRecorder for recording, allows starting and stopping the recording process, and provides a download link for the encoded AMR file. Use this to capture and save audio as AMR. ```javascript /****** 录音、编码 ******/ var amrForRecorder; var recordBtn = E('#amr-record'); var playRecordBtn = E('#amr-play-record'); var downRecordLink = E('#amr-down-record'); var recordDuration = E('#amr-record-duration'); recordBtn.onclick = function () { if (amrForRecorder && amrForRecorder.isRecording()) { recordBtn.innerHTML = '开始录音'; playRecordBtn.removeAttribute('disabled'); amrForRecorder.finishRecord().then(() => { downRecordLink.href = window.URL.createObjectURL(amrForRecorder.getBlob()); downRecordLink.innerHTML = '下载录音amr文件'; recordDuration.innerHTML = amrForRecorder.getDuration().toFixed(2) + '\''; }); } else { recordBtn.innerHTML = '停止录音'; playRecordBtn.setAttribute('disabled', true); amrForRecorder = new BenzAMRRecorder(); amrForRecorder.initWithRecord().then(() => { amrForRecorder.startRecord(); }).catch(function(e) { alert(e.message || e.name || JSON.stringify(e)); }); // 绑定事件 amrForRecorder.onPlay(function () { console.log('Recorder Event: play'); playRecordBtn.innerHTML = '停止播放'; }); amrForRecorder.onStop(function () { console.log('Recorder Event: stop'); playRecordBtn.innerHTML = '播放录音'; }); amrForRecorder.onEnded(function () { console.log('Recorder Event: ended'); playRecordBtn.innerHTML = '播放录音'; }); amrForRecorder.onAutoEnded(function () { console.log('Recorder Event: autoEnded'); }); amrForRecorder.onStartRecord(function () { console.log('Recorder Event: startRecord'); recordBtn.innerHTML = '停止录音'; }); amrForRecorder.onFinishRecord(function () { console.log('Recorder Event: finishRecord'); recordBtn.innerHTML = '开始录音'; }); } }; ``` -------------------------------- ### Require Benz AMR Recorder in Node.js Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Import the library into your JavaScript project after installation via npm. ```javascript var BenzAMRRecorder = require('benz-amr-recorder'); ``` -------------------------------- ### Get Audio Duration Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Retrieves the total duration of the audio in seconds. ```javascript amr.getDuration(); ``` -------------------------------- ### Register Play Event Listener Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Register a callback function to be executed when playback starts. New event registrations overwrite previous ones. Pass `null` to unregister. ```javascript amr.onPlay(function() { console.log('开始播放'); }); ``` -------------------------------- ### Get Blob and Download AMR File Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Obtain the recorded audio as a Blob object using `getBlob()`. This Blob can be used for downloading the AMR file or uploading it to a server. ```APIDOC ## Get Blob and Download AMR File ### Description Retrieves the encoded AMR audio data as a Blob object using the `getBlob()` method. This Blob can be utilized for downloading the file locally or sending it to a server. ### Methods - **getBlob()**: Returns the recorded audio as a Blob object. Returns `null` if no recording has been made or if the recording is not yet finished. ### Request Example ```javascript // Download recorded file document.getElementById('btn-download').addEventListener('click', function () { var blob = amrRec.getBlob(); if (!blob) { alert('No recording available or recording not finished'); return; } var url = window.URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = 'recording-' + Date.now() + '.amr'; a.click(); window.URL.revokeObjectURL(url); console.log('Download triggered, file size: ' + blob.size + ' bytes'); }); // Upload to server function uploadAMR(amr) { var blob = amr.getBlob(); if (!blob) return; var formData = new FormData(); formData.append('voice', blob, 'voice.amr'); fetch('/api/upload-voice', { method: 'POST', body: formData }) .then(function (res) { return res.json(); }) .then(function (data) { console.log('Upload successful:', data); }) .catch(function (e) { console.error('Upload failed:', e); }); } ``` ``` -------------------------------- ### Control Playback Position: setPosition / getCurrentPosition Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Use setPosition(time) to jump to a specific second without changing the play/pause state. Use getCurrentPosition() to get the current playback time in seconds. Ensure the audio is initialized with initWithUrl before using these methods. ```javascript var amr = new BenzAMRRecorder(); amr.initWithUrl('path/to/voice.amr').then(function () { amr.play(); // 跳转到第 5 秒 document.getElementById('btn-seek-5').onclick = function () { amr.setPosition(5.0); }; // 进度条拖动 var progressBar = document.getElementById('progress'); progressBar.oninput = function () { var targetTime = (this.value / 100) * amr.getDuration(); amr.setPosition(targetTime); }; // 定时刷新进度条 setInterval(function () { if (amr.isPlaying()) { var pos = amr.getCurrentPosition(); var duration = amr.getDuration(); progressBar.value = (pos / duration * 100).toFixed(1); console.log('当前进度:' + pos.toFixed(2) + ' / ' + duration.toFixed(2) + ' 秒'); } }, 500); }); ``` -------------------------------- ### Download recorded AMR audio Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Get the recorded audio as a Blob and initiate a download by creating a temporary URL. ```javascript window.location.href = window.URL.createObjectURL(amr.getBlob()); ``` -------------------------------- ### Play or Resume Audio Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md If the audio is paused, it resumes playback. Otherwise, it starts playing from the beginning. Available since version 1.1.0. ```javascript amr.playOrResume(); ``` -------------------------------- ### Playback Control: setPosition / getCurrentPosition Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Control playback by seeking to a specific time or getting the current playback position. `setPosition(time)` jumps to a specified second without changing the play/pause state. `getCurrentPosition()` returns the current playback time in seconds. ```APIDOC ## setPosition(time) ### Description Jumps playback to a specified time in seconds without altering the current play/pause state. ### Parameters #### Path Parameters - **time** (number) - Required - The time in seconds to seek to. ### Method `setPosition` ## getCurrentPosition() ### Description Gets the current playback position in seconds. ### Method `getCurrentPosition` ### Response #### Success Response (200) - **position** (number) - The current playback time in seconds. ### Request Example ```javascript var amr = new BenzAMRRecorder(); amr.initWithUrl('path/to/voice.amr').then(function () { amr.play(); // Jump to 5 seconds amr.setPosition(5.0); // Progress bar drag var progressBar = document.getElementById('progress'); progressBar.oninput = function () { var targetTime = (this.value / 100) * amr.getDuration(); amr.setPosition(targetTime); }; // Timer to refresh progress bar setInterval(function () { if (amr.isPlaying()) { var pos = amr.getCurrentPosition(); var duration = amr.getDuration(); progressBar.value = (pos / duration * 100).toFixed(1); console.log('Current progress: ' + pos.toFixed(2) + ' / ' + duration.toFixed(2) + ' seconds'); } }, 500); }); ``` ``` -------------------------------- ### Get AMR Blob Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Obtains a Blob object representing the AMR audio file, which can be used for downloading. ```javascript amr.getBlob(); ``` -------------------------------- ### Get Current Playback Position Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Returns the current playback position in seconds (as a floating-point number). Available since version 1.1.0. ```javascript amr.getCurrentPosition(); ``` -------------------------------- ### Get Blob and Download AMR File Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Retrieve the encoded AMR audio as a Blob object using getBlob(). This Blob can be used for downloading the file or uploading it to a server. Ensure a recording has been finished before calling getBlob(). ```javascript // 下载录音文件 document.getElementById('btn-download').addEventListener('click', function () { var blob = amrRec.getBlob(); if (!blob) { alert('尚未录音或录音未完成'); return; } var url = window.URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = 'recording-' + Date.now() + '.amr'; a.click(); window.URL.revokeObjectURL(url); console.log('下载已触发,文件大小:' + blob.size + ' bytes'); }); // 上传到服务器 function uploadAMR(amr) { var blob = amr.getBlob(); if (!blob) return; var formData = new FormData(); formData.append('voice', blob, 'voice.amr'); fetch('/api/upload-voice', { method: 'POST', body: formData }) .then(function (res) { return res.json(); }) .then(function (data) { console.log('上传成功:', data); }) .catch(function (e) { console.error('上传失败:', e); }); } ``` -------------------------------- ### Initialization Methods Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Methods to initialize the BenzAMRRecorder object with different data sources or recording capabilities. ```APIDOC ## isInit() ### Description Checks if the AMR recorder object has been initialized. ### Method `isInit()` ### Returns - `boolean`: True if initialized, false otherwise. ``` ```APIDOC ## initWithArrayBuffer(array) ### Description Initializes the recorder with raw array buffer data. ### Method `initWithArrayBuffer(array: Float32Array)` ### Parameters #### Path Parameters - **array** (Float32Array) - Required - The array buffer data to initialize with. ### Returns - `Promise`: A promise that resolves when initialization is complete. ``` ```APIDOC ## initWithBlob(blob) ### Description Initializes the recorder with a Blob object, typically from a file input. ### Method `initWithBlob(blob: Blob)` ### Parameters #### Path Parameters - **blob** (Blob) - Required - The Blob object to initialize with. ### Returns - `Promise`: A promise that resolves when initialization is complete. ``` ```APIDOC ## initWithUrl(url) ### Description Initializes the recorder by fetching AMR data from a URL. ### Method `initWithUrl(url: string)` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the AMR file. ### Returns - `Promise`: A promise that resolves when initialization is complete. ``` ```APIDOC ## initWithRecord() ### Description Initializes the recorder for recording audio from the microphone. ### Method `initWithRecord()` ### Returns - `Promise`: A promise that resolves when initialization for recording is complete. ``` -------------------------------- ### Initialize BenzAMRRecorder for Recording Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Initialize the recorder for capturing audio from the microphone using `initWithRecord`. This method requires user gesture to request microphone permissions. ```javascript var amrRec = new BenzAMRRecorder(); document.getElementById('btn-init-record').addEventListener('click', function () { amrRec.initWithRecord() .then(function () { console.log('麦克风权限已获取,可以开始录音'); }) .catch(function (e) { console.error('无法获取麦克风权限:', e.message); // 常见原因:用户拒绝、非 HTTPS 环境 }); }); ``` -------------------------------- ### Initialize BenzAMRRecorder with a Blob (File Input) Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Load a local AMR file selected via a file input using `initWithBlob`. This method accepts a Blob object and prepares the audio for immediate playback. ```javascript var amr = new BenzAMRRecorder(); var fileInput = document.getElementById('amr-file'); fileInput.addEventListener('change', function () { var file = this.files[0]; if (!file) return; amr = new BenzAMRRecorder(); // 每次选择新文件重新创建实例 amr.initWithBlob(file) .then(function () { console.log('文件加载成功,时长:' + amr.getDuration().toFixed(2) + ' 秒'); }) .catch(function (e) { console.error('文件解析失败:', e.message); }); }); document.getElementById('btn-play-file').addEventListener('click', function () { if (amr.isInit()) { amr.play(); } }); ``` -------------------------------- ### Initialize for Recording Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Requests microphone access and initializes the recorder for recording audio. ```APIDOC ## Initialize for Recording `initWithRecord()` requests microphone permissions and sets up the recorder for capturing audio. Must be called within a user gesture event. ### Description Initializes the recorder in recording mode, requesting microphone access. ### Method `amrRec.initWithRecord(): Promise` ### Parameters (None) ### Request Example ```javascript var amrRec = new BenzAMRRecorder(); document.getElementById('btn-init-record').addEventListener('click', function () { amrRec.initWithRecord() .then(function () { console.log('Microphone permission granted, ready to record'); }) .catch(function (e) { console.error('Failed to get microphone permission: ', e.message); // Common reasons: user denied, non-HTTPS environment }); }); ``` ### Response #### Success Response - The Promise resolves when microphone permissions are granted and the recording environment is ready. #### Response Example (No specific response body, Promise resolution indicates success) ### Error Handling - The Promise rejects if microphone permissions are denied or cannot be obtained. ``` -------------------------------- ### Initialize BenzAMRRecorder with a URL Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Load an AMR file from a URL using `initWithUrl`. This method returns a Promise and should ideally be called within a user interaction event to comply with browser autoplay policies. ```javascript var amr = new BenzAMRRecorder(); document.getElementById('btn-load').addEventListener('click', function () { amr.initWithUrl('https://example.com/audio/voice.amr') .then(function () { console.log('加载完毕,时长:' + amr.getDuration().toFixed(2) + ' 秒'); amr.play(); }) .catch(function (e) { console.error('加载失败:', e.message); }); }); ``` -------------------------------- ### Initialize with URL Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Loads an AMR audio file from a given URL using XHR and decodes it. Returns a Promise. ```APIDOC ## Initialize with URL `initWithUrl(url)` loads an AMR file from a URL and decodes it. Recommended to call within user interaction events. ### Description Initializes the recorder with an AMR audio file fetched from a URL. ### Method `amr.initWithUrl(url: string): Promise` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the AMR audio file. ### Request Example ```javascript var amr = new BenzAMRRecorder(); document.getElementById('btn-load').addEventListener('click', function () { amr.initWithUrl('https://example.com/audio/voice.amr') .then(function () { console.log('Loaded successfully, duration: ' + amr.getDuration().toFixed(2) + ' seconds'); amr.play(); }) .catch(function (e) { console.error('Loading failed: ', e.message); }); }); ``` ### Response #### Success Response - The Promise resolves when the audio is loaded and decoded. #### Response Example (No specific response body, Promise resolution indicates success) ### Error Handling - The Promise rejects if the audio fails to load or decode. ``` -------------------------------- ### Initialize with Blob Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Initializes the recorder with an AMR audio file provided as a Blob object. ```APIDOC ## Initialize with Blob `initWithBlob(blob)` accepts a Blob object, typically from a file input, and decodes it. ### Description Initializes the recorder with an AMR audio file provided as a Blob. ### Method `amr.initWithBlob(blob: Blob): Promise` ### Parameters #### Path Parameters - **blob** (Blob) - Required - The Blob object containing the AMR audio data. ### Request Example ```html ``` ```javascript var amr = new BenzAMRRecorder(); var fileInput = document.getElementById('amr-file'); fileInput.addEventListener('change', function () { var file = this.files[0]; if (!file) return; amr = new BenzAMRRecorder(); // Re-create instance for new file amr.initWithBlob(file) .then(function () { console.log('File loaded successfully, duration: ' + amr.getDuration().toFixed(2) + ' seconds'); }) .catch(function (e) { console.error('File parsing failed: ', e.message); }); }); document.getElementById('btn-play-file').addEventListener('click', function () { if (amr.isInit()) { amr.play(); } }); ``` ### Response #### Success Response - The Promise resolves when the audio is loaded and decoded. #### Response Example (No specific response body, Promise resolution indicates success) ### Error Handling - The Promise rejects if the Blob data is not a valid AMR format or fails to decode. ``` -------------------------------- ### Recording Control: startRecord / finishRecord / cancelRecord Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Manage the audio recording process. `initWithRecord()` requests microphone permissions, `startRecord()` begins recording, `finishRecord()` stops recording and encodes audio, and `cancelRecord()` discards the recording. ```APIDOC ## Recording Control: startRecord / finishRecord / cancelRecord ### Description Manages the audio recording lifecycle. `initWithRecord()` must be called first to obtain microphone access. `startRecord()` initiates the recording, `finishRecord()` stops it and encodes the audio as AMR, returning a Promise. `cancelRecord()` discards the current recording. ### Methods - **initWithRecord()**: Initializes the recorder and requests microphone permissions. Returns a Promise. - **startRecord()**: Starts the audio recording process. - **finishRecord()**: Stops the recording and encodes the audio into AMR format. Returns a Promise. - **cancelRecord()**: Aborts the current recording session. - **isRecording()**: Returns a boolean indicating if recording is currently in progress. ### Request Example ```javascript var amrRec = new BenzAMRRecorder(); // Step 1: Initialize (bind to user click) document.getElementById('btn-init').addEventListener('click', function () { amrRec.initWithRecord().then(function () { console.log('Microphone ready'); }); }); // Step 2: Start recording document.getElementById('btn-start').addEventListener('click', function () { amrRec.onStartRecord(function () { console.log('🎙 Recording...'); }); amrRec.startRecord(); console.log('Is recording:', amrRec.isRecording()); // true }); // Step 3: Finish recording and play document.getElementById('btn-finish').addEventListener('click', function () { amrRec.onFinishRecord(function () { console.log('Recording finished, duration: ' + amrRec.getDuration().toFixed(2) + ' seconds'); }); amrRec.finishRecord().then(function () { amrRec.play(); // Play back the recorded audio immediately }); }); // Cancel recording document.getElementById('btn-cancel').addEventListener('click', function () { amrRec.cancelRecord(); console.log('Recording cancelled'); }); ``` ``` -------------------------------- ### Convert MP3/OGG to AMR using initWithUrl Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Load MP3 or OGG files using `initWithUrl()` to automatically decode and re-encode them to AMR format using AudioContext. Ensure the browser natively supports the input audio format. The conversion is initiated by a user click event to comply with autoplay policies. ```javascript var converter = new BenzAMRRecorder(); document.getElementById('btn-convert').addEventListener('click', function () { // 需要浏览器原生支持该格式(如 Chrome 支持 MP3) converter.initWithUrl('path/to/music.mp3') .then(function () { console.log('转换完成,AMR 时长:' + converter.getDuration().toFixed(2) + ' 秒'); // 下载转换后的 AMR 文件 var blob = converter.getBlob(); var url = window.URL.createObjectURL(blob); window.location.href = url; }) .catch(function (e) { console.error('转换失败(可能浏览器不支持该格式):', e.message); }); }); ``` -------------------------------- ### Initialize AMR recorder for recording Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Prepare the recorder for capturing audio input. This asynchronous method returns a Promise that resolves when recording is ready. ```javascript /** * 初始化录音 * @return {Promise} */ amr.initWithRecord(); ``` -------------------------------- ### Initialize AMR recorder with a URL Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initialize the recorder by loading an AMR audio file from a specified URL. This asynchronous operation returns a Promise. ```javascript /** * 使用 url 初始化 * @param {string} url * @return {Promise} */ amr.initWithUrl(url); ``` -------------------------------- ### Register StartRecord Event Listener Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Register a callback function to be executed when recording begins. Pass `null` to unregister. ```javascript amr.onStartRecord(function() { console.log('开始录音'); }); ``` -------------------------------- ### Convenience Playback Methods Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Provides combined methods for simplified playback control logic, suitable for single-button interfaces. ```APIDOC ## Convenience Playback Methods `playOrResume()`, `pauseOrResume()`, and `playOrPauseOrResume()` simplify playback control logic. ### Description Offers combined playback actions for simplified UI interactions. ### Methods - **`playOrResume(): void`**: If not paused, plays from the beginning. If paused, resumes playback. - **`pauseOrResume(): void`**: Toggles between pausing and resuming playback. - **`playOrPauseOrResume(): void`**: Handles multiple states: plays from start if stopped, pauses if playing, resumes if paused. ### Usage Example ```javascript var amr = new BenzAMRRecorder(); amr.initWithUrl('path/to/voice.amr').then(function () { // Single button for play/resume document.getElementById('btn-play-or-resume').onclick = function () { amr.playOrResume(); }; // Single button to toggle pause/resume document.getElementById('btn-toggle-pause').onclick = function () { amr.pauseOrResume(); }; // All-in-one smart button document.getElementById('btn-smart').onclick = function () { amr.playOrPauseOrResume(); }; }); ``` ``` -------------------------------- ### Initialize BenzAMRRecorder with ArrayBuffer Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Load audio data from an ArrayBuffer using `initWithArrayBuffer`. This is useful when audio data is obtained via Fetch API or other binary data sources. The library attempts to convert non-AMR data to AMR. ```javascript var amr = new BenzAMRRecorder(); fetch('https://example.com/audio/voice.amr') .then(function (res) { return res.arrayBuffer(); }) .then(function (buffer) { return amr.initWithArrayBuffer(buffer); }) .then(function () { console.log('ArrayBuffer 初始化成功'); amr.play(); }) .catch(function (e) { console.error('初始化失败:', e.message); }); ``` -------------------------------- ### Initialize with ArrayBuffer Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Initializes the recorder with audio data provided as an ArrayBuffer. Attempts to convert non-AMR data to AMR. ```APIDOC ## Initialize with ArrayBuffer `initWithArrayBuffer(array)` accepts `Float32Array` or `ArrayBuffer`. It attempts to decode non-AMR data using the browser's AudioContext and convert it to AMR. ### Description Initializes the recorder with audio data in ArrayBuffer format. ### Method `amr.initWithArrayBuffer(array: ArrayBuffer | Float32Array): Promise` ### Parameters #### Path Parameters - **array** (ArrayBuffer | Float32Array) - Required - The audio data buffer. ### Request Example ```javascript var amr = new BenzAMRRecorder(); fetch('https://example.com/audio/voice.amr') .then(function (res) { return res.arrayBuffer(); }) .then(function (buffer) { return amr.initWithArrayBuffer(buffer); }) .then(function () { console.log('ArrayBuffer initialization successful'); amr.play(); }) .catch(function (e) { console.error('Initialization failed: ', e.message); }); ``` ### Response #### Success Response - The Promise resolves when the audio data is processed and decoded. #### Response Example (No specific response body, Promise resolution indicates success) ### Error Handling - The Promise rejects if the ArrayBuffer data cannot be processed or decoded. ``` -------------------------------- ### Initialize AMR recorder with ArrayBuffer Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initialize the recorder using raw audio data provided as a Float32Array. This method returns a Promise that resolves upon successful initialization. ```javascript /** * 使用浮点数据初始化 * @param {Float32Array} array * @return {Promise} */ amr.initWithArrayBuffer(array); ``` -------------------------------- ### Play AMR audio from a local file Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initialize the recorder with an AMR audio file selected by the user via an input element. The `initWithBlob` method accepts a File object. ```html ``` ```javascript var amr = new BenzAMRRecorder(); var amrFileObj = document.getElementById('amr-file'); amrFileObj.onchange = function() { amr.initWithBlob(this.files[0]).then(function() { amr.play(); }); } ``` -------------------------------- ### Load and Play AMR from URL Source: https://github.com/benzleung/benz-amr-recorder/blob/master/demo.html Initializes the BenzAMRRecorder with an AMR file from a URL and enables playback controls. Use this to play pre-existing AMR audio files. ```javascript (function () { function E(selector) { return document.querySelector(selector); } /**** 解码、播放 ****/ var amr; var loadDemoBtn = E('#amr-load'); var loadAmrFile = E('#amr-file'); var playBtn = E('#amr-play'); var stopBtn = E('#amr-stop'); var progressCtrl = E('#amr-progress'); var isDragging = false; var cur = E('#amr-cur'); var duration = E('#amr-duration'); setInterval(function () { if (amr) { cur.innerHTML = amr.getCurrentPosition().toFixed(2) + '\''; if (!isDragging) { progressCtrl.value = amr.getCurrentPosition().toFixed(2); } } else { cur.innerHTML = '0\' } }, 10); loadDemoBtn.onclick = function() { amr = new BenzAMRRecorder(); loadDemoBtn.setAttribute('disabled', true); loadAmrFile.setAttribute('disabled', true); playBtn.setAttribute('disabled', true); stopBtn.setAttribute('disabled', true); progressCtrl.setAttribute('disabled', true); amr.initWithUrl('./res/mario.amr').then(function () { loadDemoBtn.removeAttribute('disabled'); loadAmrFile.removeAttribute('disabled'); playBtn.removeAttribute('disabled'); stopBtn.removeAttribute('disabled'); progressCtrl.removeAttribute('disabled'); progressCtrl.setAttribute('max', amr.getDuration()); duration.innerHTML = amr.getDuration().toFixed(2) + '\''; }); // 绑定事件 amr.onPlay(function () { console.log('Event: play'); playBtn.innerHTML = '暂停'; }); amr.onStop(function () { console.log('Event: stop'); playBtn.innerHTML = '播放'; }); amr.onPause(function () { console.log('Event: pause'); playBtn.innerHTML = '继续'; }); amr.onResume(function () { console.log('Event: resume'); playBtn.innerHTML = '暂停'; }); amr.onEnded(function () { console.log('Event: ended'); playBtn.innerHTML = '播放'; }); amr.onAutoEnded(function () { console.log('Event: autoEnded'); }); amr.onStartRecord(function () { console.log('Event: startRecord'); }); amr.onFinishRecord(function () { console.log('Event: finishRecord'); }); amr.onCancelRecord(function () { console.log('Event: cancelRecord'); }); }; playBtn.onclick = function () { amr.playOrPauseOrResume(); }; stopBtn.onclick = function () { amr.stop(); }; progressCtrl.onmousedown = function () { isDragging = true; }; progressCtrl.onmouseup = function () { isDragging = false; }; progressCtrl.onchange = function (e) { amr.setPosition(e.target.value); }; loadAmrFile.onchange = function() { amr = new BenzAMRRecorder(); loadDemoBtn.setAttribute('disabled', true); loadAmrFile.setAttribute('disabled', true); playBtn.setAttribute('disabled', true); amr.initWithBlob(this.files[0]).then(function () { loadDemoBtn.removeAttribute('disabled'); loadAmrFile.removeAttribute('disabled'); playBtn.removeAttribute('disabled'); duration.innerHTML = amr.getDuration().toFixed(2) + '\''; }); // 绑定事件 amr.onPlay(function () { console.log('Event: play'); playBtn.innerHTML = '停止'; }); amr.onStop(function () { console.log('Event: stop'); playBtn.innerHTML = '播放'; }); amr.onEnded(function () { console.log('Event: ended'); playBtn.innerHTML = '播放'; }); amr.onAutoEnded(function () { console.log('Event: autoEnded'); }); amr.onStartRecord(function () { console.log('Event: startRecord'); }); amr.onFinishRecord(function () { console.log('Event: finishRecord'); }); amr.onCancelRecord(function () { console.log('Event: cancelRecord'); }); }; ``` -------------------------------- ### Browser Compatibility Check Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Static methods to check if the browser supports AMR playback or recording capabilities before initializing any instances. ```APIDOC ## Browser Compatibility Check `BenzAMRRecorder.isPlaySupported()` and `BenzAMRRecorder.isRecordSupported()` are static methods to check browser capabilities. ### Description Checks if the current browser supports AMR playback or recording. ### Usage ```javascript // Check for playback support if (!BenzAMRRecorder.isPlaySupported()) { alert('AMR playback is not supported in this browser.'); } // Check for recording support if (!BenzAMRRecorder.isRecordSupported()) { alert('Recording is not supported in this browser (getUserMedia API required).'); } else { console.log('Browser supports recording.'); } ``` ``` -------------------------------- ### Check Recording Support (Static) Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md A static method to check if the browser supports audio recording. Available since version 1.1.0. Note: Call this on the class, not an instance. ```javascript BenzAMRRecorder.isRecordSupported(); ``` -------------------------------- ### Format Conversion: MP3/OGG to AMR Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Load browser-native audio formats like MP3 or OGG using `initWithUrl()`. The library automatically decodes and re-encodes them to AMR using AudioContext for pure frontend format conversion. ```APIDOC ## initWithUrl() ### Description Loads an audio file from a URL and prepares it for conversion to AMR format. This method is useful for converting existing audio files (like MP3 or OGG) that are natively supported by the browser. ### Method `initWithUrl(url: string)` ### Parameters #### Path Parameters - **url** (string) - Required - The URL of the audio file to load. ### Response Example ```javascript var converter = new BenzAMRRecorder(); document.getElementById('btn-convert').addEventListener('click', function () { // Requires browser native support for the format (e.g., Chrome supports MP3) converter.initWithUrl('path/to/music.mp3') .then(function () { console.log('Conversion complete, AMR duration: ' + converter.getDuration().toFixed(2) + ' seconds'); // Download the converted AMR file var blob = converter.getBlob(); var url = window.URL.createObjectURL(blob); window.location.href = url; }) .catch(function (e) { console.error('Conversion failed (browser may not support this format): ', e.message); }); }); ``` ``` -------------------------------- ### Event Handling Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Register callback functions for various audio events. Note that events do not stack; new registrations overwrite old ones. Callbacks can be unbound by passing `null`. ```APIDOC ## onPlay ### Description Registers a callback function to be executed when playback starts. ### Method amr.onPlay(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on play, or null to unbind. ``` ```APIDOC ## onStop ### Description Registers a callback function to be executed when playback stops (including when playback ends). ### Method amr.onStop(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on stop, or null to unbind. ``` ```APIDOC ## onPause ### Description Registers a callback function to be executed when playback is paused. ### Method amr.onPause(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on pause, or null to unbind. ``` ```APIDOC ## onResume ### Description Registers a callback function to be executed when playback resumes from a paused state. ### Method amr.onResume(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on resume, or null to unbind. ``` ```APIDOC ## onEnded ### Description Registers a callback function to be executed when playback finishes normally. ### Method amr.onEnded(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on ended, or null to unbind. ``` ```APIDOC ## onAutoEnded ### Description Registers a callback function to be executed when playback automatically ends at the end of the audio. ### Method amr.onAutoEnded(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on auto ended, or null to unbind. ``` ```APIDOC ## onStartRecord ### Description Registers a callback function to be executed when recording starts. ### Method amr.onStartRecord(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on start record, or null to unbind. ``` ```APIDOC ## onFinishRecord ### Description Registers a callback function to be executed when recording finishes. ### Method amr.onFinishRecord(fn: Function | null) ### Parameters - **fn** (Function | null) - The callback function to execute on finish record, or null to unbind. ``` -------------------------------- ### Other Utility Methods Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Miscellaneous methods for retrieving audio information, managing resources, and checking browser support. ```APIDOC ## getDuration ### Description Retrieves the total duration of the audio in seconds. ### Method amr.getDuration(): number ### Returns - **number** - The duration of the audio in seconds (floating-point). ``` ```APIDOC ## getBlob ### Description Retrieves the recorded audio as a Blob object, which can be used for downloading. ### Method amr.getBlob(): Blob ### Returns - **Blob** - A Blob object representing the AMR audio file. ``` ```APIDOC ## destroy ### Description Releases all resources associated with the recorder, including audio/file data and event listeners. The object becomes unusable after this call. Available since version 1.1.4. ### Method amr.destroy() ``` ```APIDOC ## BenzAMRRecorder.isPlaySupported ### Description A static method to check if the browser supports audio playback functionality. ### Method BenzAMRRecorder.isPlaySupported(): boolean ### Returns - **boolean** - `true` if playback is supported, `false` otherwise. ``` ```APIDOC ## BenzAMRRecorder.isRecordSupported ### Description A static method to check if the browser supports audio recording functionality. ### Method BenzAMRRecorder.isRecordSupported(): boolean ### Returns - **boolean** - `true` if recording is supported, `false` otherwise. ``` -------------------------------- ### Initialize AMR recorder with a Blob Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Initialize the recorder using a Blob object, typically obtained from a file input or other sources. This method returns a Promise. ```javascript /** * 使用 Blob 对象初始化( ) * @param {Blob} blob * @return {Promise} */ amr.initWithBlob(blob); ``` -------------------------------- ### Check if AMR recorder is initialized Source: https://github.com/benzleung/benz-amr-recorder/blob/master/README.md Use the `isInit()` method to determine if the recorder object has been successfully initialized. ```javascript /** * 是否已经初始化 * @return {boolean} */ amr.isInit(); ``` -------------------------------- ### Check Browser Compatibility for AMR Playback and Recording Source: https://context7.com/benzleung/benz-amr-recorder/llms.txt Use static methods to check if the browser supports AMR playback or recording before initializing the library. This helps provide a better user experience by informing users of limitations. ```javascript // 仅检测,不实例化 if (!BenzAMRRecorder.isPlaySupported()) { alert('当前浏览器不支持 AMR 播放,请使用 Chrome / Firefox / Safari 等现代浏览器。'); } if (!BenzAMRRecorder.isRecordSupported()) { alert('当前浏览器不支持录音功能(需要 getUserMedia API 支持)。'); } else { console.log('浏览器支持录音,可以继续初始化。'); } ```