The realization method of converting audio files into binary packets and storing them in redis


Functional requirements:

1、 Get the local audio file and parse it into binary data audio stream

2、 The audio stream is converted into a byte [] array, and the packet is carried out according to the number of bytes of the specified size

3、 The audio stream is divided into several packets and cached in redis database in the form of list list

4、 The data is obtained from redis database and converted into audio stream, which is output to browser to play and realize audio download function

The procedure is as follows:

1. In SpringBootpom.xml Add redis dependency to file

<! -- redis dependence -- >

2. Add the following configuration in the springboot configuration file

#Service port
 port: 8080

#Reids configuration
 Host: # redis server address
 Database: 1 # redis database index (default is 0)
 Port: 6379 ා redis server connection port
 Password: redis server connection password (default is blank)
 Max active: 8 ා the maximum number of connections in the connection pool (use a negative value to indicate that there is no limit)
 Max wait: - 1ms # maximum blocking waiting time of connection pool (negative value indicates no limit)
 Max idle: 8 ා the maximum free connection in the connection pool
 Min idle: 0 ා the minimum free connection in the connection pool
 Timeout: 3000ms ා connection timeout (MS)

3. Create redistemplate object and operate redisredisredistemplate

To put it more popular In order to make the spring framework system more convenient to access the functions of redis, redistemplate is actually the spring framework’s encapsulation of jedis It is the template of using redis in spring data redis.

 *Create redistemplate object and operate redis

 private RedisTemplate<String,Object> redisTemplate;

4. Main business data processing read audio files for conversion and storage

Through FileInputStream object, the audio file is converted into a byte [] array for subcontracting. The byte data of the packet is added to the list collection. The parameter list element is added in batch by calling the opsforlist(). Rightpushall method of redistemplate object, and stored in the list data format of redis.

 *Get the file, convert the file into a byte [] array, and store it in redis
 public Object getsty() throws Exception {
 File file = new File("E:/zmj-3011-32779/12121.mp3");
 FileInputStream inputFile = new FileInputStream(file);
 byte[] buffer = new byte[(int) (file.length() * 1)]; (buffer); // file parsing adds bytes to buffer []

 Int vicelength = 180; // packet size per byte
 int viceNumber = (int)  Math.ceil ( buffer.length  /(double) vicelength); // how many packets are saved
 int from, to;
 List listrk = new ArrayList();
 For (int i = 0; I < vicenumber; I + +) {// splits the complete audio buffer [] circularly
  ioentity ioe=new ioentity();
  from=(int) (i*viceLength);
  listrk.add ( Arrays.copyOfRange (buffer, from, to)); // copy and generate a new array by byte range and add it to the list
 redisTemplate.opsForList (). Rightpushall ("audio, listrk); // batch addition of redistemplate, which is stored in the form of a list
 Return "redis successfully entered the warehouse!";

Redis client store results:

It can be seen that only one key is stored, value is stored in the form of a list, and audio files are stored in an array of 180 bytes, with a total of 2634. There is no cache time set here, so it will not time out.

6. Get audio data from redis database cache for analysis

Through the redis object redisTemplate.opsForList (). Range method gets the value of cache, receives and traverses through list collection, merges to generate a new byte array, outputs byte array through OutputStream object, and browser automatically parses binary audio stream file.

 *Analyze audio by merging byte [] array from redis
 public Object getKey(HttpServletResponse response) throws Exception{
 OutputStream os = response.getOutputStream();
 List list = redisTemplate.opsForList (). Range ("audio", 0, - 1); // get the value of the specified interval through key, store it in list mode, and receive it with list collection

 //Merge audio
 List<byte[]> blist = list;
 int lengthTotal = 0;
 for (byte[] item : blist) {
  lengthTotal += item.length;
 byte[] totalByte = new byte[lengthTotal];
 int begin = 0;
 for (byte[] item : blist) {
  // System.arraycopy (original array, original array start position, target array, target array start position, copy length);
  System.arraycopy(item, 0, totalByte, begin, item.length);
  begin += item.length;
 os.write (totalbyte); // output the merged array through the OutputStream object

 Return "; // OutputStream object outputs the stream. If it is empty, the browser will automatically parse the audio stream for us

The first analysis method is as follows

The browser sends a request to get the audio binary stream. The browser parses and automatically generates a player to play the audio and additional download functions.

The second analysis method is as follows

Define audio tag in HTML page, create XMLHttpRequest object to initiate request, and parse through audio tag.

<audio width="200" controls="controls"></audio>


 function agf() {
 //Creating an XMLHttpRequest object
 var xhr = new XMLHttpRequest();
 //Configure the request mode, request address and whether to synchronize'POST', '/getkey', true);
 //Set the request result type to blob
 xhr.responseType = 'blob';
 //Request success callback function
 xhr.onload = function(e) {
 if ( this.status  ==200) {// request successful
  //Get blob object
  var blob = this.response;
  //Get blob object地址,并把值赋给容器
  $("#sound").attr("src", URL.createObjectURL(blob));


This article on the audio file into binary sub package storage to redis (strange skills operation) of the article introduced here, more related audio files converted to binary sub package stored in redis content, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!