Preface
During the development of the mini program, there is a requirement to implement the recording function and play the recording and upload the recording to the server. During the development process, the Taro framework was used, and the recording function was implemented through the () interface, uploading the recording to the server through the interface, and playing the recording was implemented through the () interface. The following will introduce in detail how the entire process is implemented.
Mini Program Recording
First get the recording manager module:
const recorderManager = ();
Register the recording monitoring event when the component is mounted:
useEffect(() => { // The monitor recording starts (() => { ('Start recording'); }); // Monitor recording is paused (() => { ('Pause recording'); }); // Continue the monitor recording (() => { ('Continue recording'); }); // Monitor recording stops ((res) => { if ( < 1000) { ({ title: 'The recording time is too short', duration: 1000, icon: 'none', }); } else { ('Stop recording'); fileUpload(); } }); (() => { ({ title: 'The recording failed! ', duration: 1000, icon: 'none', }); }); }, []);
In the callback function of recording onStop, we can get the temporary address of the recording, but this address has a valid period, so we need to upload the recording to the server background for saving, so that we can use it normally in the future.
In the onStop callback function, we call the fileUpload function to achieve file upload. The implementation of the fileUpload function is as follows:
const fileUpload = (tempFilePath) => { ({ url: 'http://127.0.0.1:7001/record', // Server address filePath: tempFilePath, name: 'file', // Fill in this casually header: { 'content-type': 'multipart/form-data', // The format must be this Authorization: ('token'), }, // formData is used to transfer some information other than files formData: { record_name: 'Recitation Works', poem_id: , category: , }, success: (res) => { (res); const url = ; playAudio(url); // Play recording }, fail: (error) => { ('failed!'); (error); }, }); };
The point to be noted is that the content-type in the header must be multipart/form-data.
Handling of recording events
The first time you click handleClick, the recording will be triggered, and then the recording will be determined based on the current status. handleComplete is used to stop recording.
const handleClick = () => { const curPause = pause; setPause(!curPause); if (firstRecord) { setfirstRecord(false); ({ duration: 60000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 192000, format: 'mp3', frameSize: 50, }); ({ title: 'Start recording', duration: 1000, icon: 'none', }); } else { if (curPause) { (); // Pause recording } else { (); // Continue recording } } }; const handleComplete = () => { (); // Stop recording };
Implement recording storage in the background and return the recording address
Most blogs on the Internet do not cover this content. Let me introduce how to implement it. I use Alibaba’s backend framework.
The official documentation is available for uploading files:File upload. The first one we use hereFileMode to implement。
Because the framework has a Multipart plug-in built-in, it can parse uploaded multipart/form-data data.
First, now write the multipart configuration in the configuration file:
= (app) => { const config = (exports = {}); ... = { mode: 'file', fileSize: '50mb', } ... return { ...config, ...userConfig, }; };
Then, define the route in:
// Submit recording('/record', auth, ); existcontrollerWrite the following contents in the definition file in the directory: const Controller = require('egg').Controller; class RecordController extends Controller { async postRecord() { const { ctx } = this; const file = [0]; const { record_name, poem_id, category } = ; const res = await (file, record_name, poem_id, category); = res; } } = RecordController;
Define the specific implementation of writing in the service directory:
const Service = require('egg').Service; let OSS = require('ali-oss'); let aliInfo = { // /document_detail/ region: 'oss-cn-guangzhou', bucket: 'poem-mini-program', accessKeyId: 'xxx', //Fill in Alibaba Cloud's accessKeyId accessKeySecret: 'xxx', // Fill in Alibaba Cloud's accessKeySecret}; let client = new OSS(aliInfo); class RecordService extends Service { async postRecord(file, record_name, poem_id, category) { const url = await (file); await (url, record_name, poem_id, category); return url; } async uploadOSS(file) { const { ctx } = this; let result; try { // Process files, such as uploading them to the cloud result = await (, ); } finally { // Temporary files need to be deleted await (); } return ; } async updateRecord(url, record_name, poem_id, category) { const { ctx } = this; ('Take openid from it'); (); const openid = ; // Record user information into the database const res = await ({ record_name: record_name, record_url: url, poem_id: poem_id, category: category, openid: openid, }); } } = RecordService;
What needs to be noted here is:
- You need to register an Alibaba Cloud account and create a new storage bucket in the object storage to store audio, which is the implementation of cloud storage.
- The ali-ossnpm package needs to be installed to connect to Alibaba Cloud object storage. After receiving the temporary file uploaded by the front end in the background, the audio will be uploaded to Alibaba Cloud object storage ().
Play recording
Careful friends can notice that after uploading recordings using the interface, the playAudio function is called in the success callback to play audio. Next, let’s talk about how to play audio.
First, get audio's context object using:
const innerAudioText = ();
Like recording, when component mount is completed, register the monitoring event:
useEffect(() => { (() => { ('Start play'); }); ((e) => { ('Play exception'); (e); }); }, []);
After the recording file is uploaded successfully, call the playAudio method to play the recording:
const playAudio = (url) => { = true; = url; };
When src is assigned a value, the recording will start playing.
Summarize
This is the article about the realization of the recording function of the mini program. For more related mini program recording content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!