


How to split a recorded blob stream into multiple 5 second WAV files using JavaScript and make sure it plays normally?
Use 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

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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



When converting strings to objects in Vue.js, JSON.parse() is preferred for standard JSON strings. For non-standard JSON strings, the string can be processed by using regular expressions and reduce methods according to the format or decoded URL-encoded. Select the appropriate method according to the string format and pay attention to security and encoding issues to avoid bugs.

There are many reasons why MySQL startup fails, and it can be diagnosed by checking the error log. Common causes include port conflicts (check port occupancy and modify configuration), permission issues (check service running user permissions), configuration file errors (check parameter settings), data directory corruption (restore data or rebuild table space), InnoDB table space issues (check ibdata1 files), plug-in loading failure (check error log). When solving problems, you should analyze them based on the error log, find the root cause of the problem, and develop the habit of backing up data regularly to prevent and solve problems.

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Summary: There are the following methods to convert Vue.js string arrays into object arrays: Basic method: Use map function to suit regular formatted data. Advanced gameplay: Using regular expressions can handle complex formats, but they need to be carefully written and considered. Performance optimization: Considering the large amount of data, asynchronous operations or efficient data processing libraries can be used. Best practice: Clear code style, use meaningful variable names and comments to keep the code concise.

In order to set the timeout for Vue Axios, we can create an Axios instance and specify the timeout option: In global settings: Vue.prototype.$axios = axios.create({ timeout: 5000 }); in a single request: this.$axios.get('/api/users', { timeout: 10000 }).

Remote Senior Backend Engineer Job Vacant Company: Circle Location: Remote Office Job Type: Full-time Salary: $130,000-$140,000 Job Description Participate in the research and development of Circle mobile applications and public API-related features covering the entire software development lifecycle. Main responsibilities independently complete development work based on RubyonRails and collaborate with the React/Redux/Relay front-end team. Build core functionality and improvements for web applications and work closely with designers and leadership throughout the functional design process. Promote positive development processes and prioritize iteration speed. Requires more than 6 years of complex web application backend

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.
