


How to split a recorded blob stream into multiple 5 second WAV files using JavaScript and make sure it plays normally?
Apr 04, 2025 pm 02:39 PMUse javascript to split the recorded blob stream and generate a 5-second wav file
When recording using react-mic, I encountered a requirement: I need to split the recorded blob stream into multiple 5-second wav files. However, after trying, I found that only the first split wav file can be played normally, and the rest of the files are prompted to be corrupted.
When implementing this requirement in the front-end, we mainly face two challenges: one is how to correctly segment the blob stream, and the other is how to ensure that each segmented clip can correctly generate and play wav files. The following are code examples and solutions:
import React, { useRef, useState } from 'react' import { ReactMic, ReactMicStopEvent } from 'react-mic' import { Button } from 'antd' const AudioRecorder = () => { const [record, setRecord] = useState(false) const resRef = useRef<blob>([]) const audioChunksRef = useRef<blob>([]) const intervalRef = useRef<nodejs.timer null>(null) const firstBlob = useRef<blob undefined>(undefined) const createWavHeader = (numChannels, sampleRate, byteLength) => { const header = new ArrayBuffer(44); const view = new DataView(header); view.setUint32(0, 1380533830, false); // "RIFF" view.setUint32(4, byteLength 36, false); view.setUint32(8, 1718449184, false); // "WAVE" view.setUint32(12, 1684108385, false); // "fmt " view.setUint32(16, 16, true); // 16 for PCM view.setUint16(20, 1, true); // PCM view.setUint16(22, numChannels, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * numChannels * 2, true); view.setUint16(32, numChannels * 2, true); view.setUint16(34, 16, true); // 16 bits view.setUint32(36, 1684108385, false); // "data" view.setUint32(40, byteLength, true); return header; }; const saveFile = async() => { const chunksList = resRef.current; for (let i = 0; i { setRecord(true) audioChunksRef.current = [] // Clear the previous recording data // Split the recording intervalRef.current = setInterval(() => { const curBlob = new Blob(audioChunksRef.current, { type: 'audio/wav' }) const startIndex = audioChunksRef.current.indexOf(firstBlob.current as Blob) const blob = curBlob.slice(startIndex === -1 ? 0 : startIndex, -1, 'audio/wav') firstBlob.current = audioChunksRef.current.at(-1) // Process the current recording data console.log('Segment of current recording data:', blob) resRef.current.push(blob) }, 5000) } const stopRecording = () => { setRecord(false) intervalRef.current && clearInterval(intervalRef.current) // Clear timer} const onData = (recordedBlob: Blob) => { audioChunksRef.current.push(recordedBlob) // Save recording data} const onStop = (recordedBlob: ReactMicStopEvent) => { console.log('Recorded Completed:', recordedBlob) } const saveFile1 = () => { const chunksList = resRef.current chunksList.map(async (v, i) => { const fileName = 'aaa.wav' const file: File = new File([v], fileName, { type: 'audio/wav' }) const fileSize = file.size console.log('fileSize', fileSize) // Create a download link const url = URL.createObjectURL(file) const a = document.createElement('a') a.href = url a.download = `recording${i}.wav` // Set the name of the download file a.click() // Trigger download// Release URL resource URL.revokeObjectURL(url) }) } const saveFinalResult = () => { const fileName = 'aaa.wav' const file: File = new File(audioChunksRef.current, fileName, { type: 'audio/wav' }) const fileSize = file.size console.log('fileSize', fileSize) // Create a download link const url = URL.createObjectURL(file) const a = document.createElement('a') a.href = url a.download = `recording${Date.now()}.wav` // Set the name of the download file a.click() // Trigger download// Release URL resource URL.revokeObjectURL(url) } Return ( <div> <reactmic record="{record}" onstop="{onStop}" ondata="{onData}" mimetype="audio/wav"></reactmic> <button onclick="{startRecording}">Start recording</button> <button onclick="{stopRecording}">Stop recording</button> <button onclick="{saveFile}">Download</button> <button onclick="{saveFinalResult}">Download Final</button> </div> ) } export default AudioRecorder</blob></nodejs.timer></blob></blob>
During the process of trying to split the blob stream and generating the wav file, it was found that manually adding the wav header information would not solve the problem. The reason is that the structure of the wav file is relatively strict. If the header information is not correctly added after segmentation, the file may be corrupted.
One suggestion to solve this problem is to use the wasm version of ffmpeg, a library of audio and video processing that can be run in the browser. With it, you can easily segment the audio and generate the correct wav file format. You can consider using the ffmpeg.wasm project to implement this function.
The above is the detailed content of How to split a recorded blob stream into multiple 5 second WAV files using JavaScript and make sure it plays normally?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Ordinary investors can discover potential tokens by tracking "smart money", which are high-profit addresses, and paying attention to their trends can provide leading indicators. 1. Use tools such as Nansen and Arkham Intelligence to analyze the data on the chain to view the buying and holdings of smart money; 2. Use Dune Analytics to obtain community-created dashboards to monitor the flow of funds; 3. Follow platforms such as Lookonchain to obtain real-time intelligence. Recently, Cangming Money is planning to re-polize LRT track, DePIN project, modular ecosystem and RWA protocol. For example, a certain LRT protocol has obtained a large amount of early deposits, a certain DePIN project has been accumulated continuously, a certain game public chain has been supported by the industry treasury, and a certain RWA protocol has attracted institutions to enter.

DAI is suitable for users who attach importance to the concept of decentralization, actively participate in the DeFi ecosystem, need cross-chain asset liquidity, and pursue asset transparency and autonomy. 1. Supporters of the decentralization concept trust smart contracts and community governance; 2. DeFi users can be used for lending, pledge, and liquidity mining; 3. Cross-chain users can achieve flexible transfer of multi-chain assets; 4. Governance participants can influence system decisions through voting. Its main scenarios include decentralized lending, asset hedging, liquidity mining, cross-border payments and community governance. At the same time, it is necessary to pay attention to system risks, mortgage fluctuations risks and technical threshold issues.

To identify fake altcoins, you need to start from six aspects. 1. Check and verify the background of the materials and project, including white papers, official websites, code open source addresses and team transparency; 2. Observe the online platform and give priority to mainstream exchanges; 3. Beware of high returns and people-pulling modes to avoid fund traps; 4. Analyze the contract code and token mechanism to check whether there are malicious functions; 5. Review community and media operations to identify false popularity; 6. Follow practical anti-fraud suggestions, such as not believing in recommendations or using professional wallets. The above steps can effectively avoid scams and protect asset security.

The coordinated rise of Bitcoin, Chainlink and RWA marks the shift toward institutional narrative dominance in the crypto market. Bitcoin, as a macro hedging asset allocated by institutions, provides a stable foundation for the market; Chainlink has become a key bridge connecting the reality and the digital world through oracle and cross-chain technology; RWA provides a compliance path for traditional capital entry. The three jointly built a complete logical closed loop of institutional entry: 1) allocate BTC to stabilize the balance sheet; 2) expand on-chain asset management through RWA; 3) rely on Chainlink to build underlying infrastructure, indicating that the market has entered a new stage driven by real demand.

Is DAI suitable for long-term holding? The answer depends on individual needs and risk preferences. 1. DAI is a decentralized stablecoin, generated by excessive collateral for crypto assets, suitable for users who pursue censorship resistance and transparency; 2. Its stability is slightly inferior to USDC, and may experience slight deansal due to collateral fluctuations; 3. Applicable to lending, pledge and governance scenarios in the DeFi ecosystem; 4. Pay attention to the upgrade and governance risks of MakerDAO system. If you pursue high stability and compliance guarantees, it is recommended to choose USDC; if you attach importance to the concept of decentralization and actively participate in DeFi applications, DAI has long-term value. The combination of the two can also improve the security and flexibility of asset allocation.

The role of Ethereum smart contract is to realize decentralized, automated and transparent protocol execution. Its core functions include: 1. As the core logic layer of DApp, it supports token issuance, DeFi, NFT and other functions; 2. Automatically execute contracts through code to reduce the risks of human intervention and fraud; 3. Build a DeFi ecosystem so that users can directly conduct financial operations such as lending and transactions; 4. Create and manage digital assets to ensure uniqueness and verifiability; 5. Improve the transparency and security of supply chain and identity verification; 6. Support DAO governance and realize decentralized decision-making.

The value of stablecoins is usually pegged to the US dollar 1:1, but it will fluctuate slightly due to factors such as market supply and demand, investor confidence and reserve assets. For example, USDT fell to $0.87 in 2018, and USDC fell to around $0.87 in 2023 due to the Silicon Valley banking crisis. The anchoring mechanism of stablecoins mainly includes: 1. fiat currency reserve type (such as USDT, USDC), which relies on the issuer's reserves; 2. cryptocurrency mortgage type (such as DAI), which maintains stability by over-collateralizing other cryptocurrencies; 3. Algorithmic stablecoins (such as UST), which relies on algorithms to adjust supply, but have higher risks. Common trading platforms recommendations include: 1. Binance, providing rich trading products and strong liquidity; 2. OKX,

Which altcoins have explosive potential in 2025? The answers are as follows: 1. In the Layer2 expansion track, Arbitrum (ARB) has been expanding rapidly, with obvious daily active users, and Optimism (OP) as an Ethereum optimization protocol continues to be adopted by large-scale protocols, which are all worth paying attention; 2. Among the DeFi protocol altcoins, Aave (AAVE) has enhanced lending logic, attracted stable capital inflows due to the new version, and Curve (CRV) maintains an advantageous position in the stablecoin exchange track and has strong competitiveness; 3. In the combination of artificial intelligence projects, Fetch.ai (FET) increases attention by integrating AI and blockchain, and Ocean Pro
