首页>代码>springboot麦克风录制声音文件保存本地,可拓展ASR识别后返回>/MicAudioToWav/src/main/java/com/yafengliang/controller/RecordingController.java
/**
 * Copyright (c) 2016, 2024, All rights reserved.
 * Powered by [liangyafeng@duplicall.com] On 2024-04-01 14:58:00
 */
package com.yafengliang.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

/**
 *
 * <p>Project: MicAudioToWav - RecordingController
 * <p>@Author: liangyafeng@duplicall.com On 2024-04-01 14:58:00
 *
 * <p>@Description: 声音录制启停控制器
 */
@Controller
@Slf4j
public class RecordingController {

    private File audioFile;
    private TargetDataLine targetDataLine;

    @GetMapping(value = "/")
    public String toIndex() {
        return "index";
    }


    @PostMapping(value = "/startRecording")
    @ResponseBody
    public String startRecording() {
        try {
            AudioFormat audioFormat = new AudioFormat(
                    44100,  // 采样率  (44100Hz是目前大多数PC机都支持的采样率,若是录制其他采样率(8k,16k等),请自行修改并确保录制软件也支持该采样率)
                    16,                  // 位数
                    1,                   // 通道数
                    true,                // 是否是可变位数
                    false                // 是否是可变通道
            );
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);

            if (!AudioSystem.isLineSupported(dataLineInfo)) {
                return "Microphone not supported!";
            }

            targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
            targetDataLine.open(audioFormat);
            targetDataLine.start();

            //获取保存录音文件的目录
            String audioPath = "d:\\voice\\0";
            //创建保存目录
            File dir = new File(audioPath);
            if (!dir.exists()) {
                Files.createDirectories(dir.toPath());
            }
            //生成唯一文件名
            String fileName = UUID.randomUUID().toString() + ".wav";
            //构建保存文件的完整路径
            String filePath = audioPath + File.separator + fileName;

            audioFile = new File(filePath);

            Thread recordingThread = new Thread(() -> {
                AudioInputStream audioInputStream = new AudioInputStream(targetDataLine);
                try {
                    AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, audioFile);
                } catch (IOException e) {
                    log.error("Failed to save file:{}", e.toString());
                }
            });
            recordingThread.start();
            return "Start recording...";
        } catch (LineUnavailableException e) {
            log.error("Unable to start recording:{}", e.getMessage());
            return "Unable to start recording:" + e.getMessage();
        } catch (IOException e) {
            log.error("Failed to create folder:{}", e.toString());
            throw new RuntimeException(e);
        }
    }

    /**
     * 停止录音
     *
     * @return 停止录音
     */
    @PostMapping(value = "stopRecording")
    @ResponseBody
    public String stopRecording() {
        String processedRecording = "";
        if (targetDataLine != null) {
            targetDataLine.stop();
            targetDataLine.close();
            targetDataLine = null;
        }
        if (audioFile != null) {
            // 处理录音文件,例如发送到接口进行处理
            try {
                FileInputStream inputStream = new FileInputStream(audioFile);
                MultipartFile multipartFile = new MockMultipartFile("file", audioFile.getName(), "audio/wav", inputStream);
                processedRecording = processRecording(multipartFile);
            } catch (IOException e) {
                log.error("Description Failed to process the recording file:{}", e.toString());
            }
            if (!processedRecording.isEmpty()) {
                return processedRecording;
            } else {
                return "connect asr error";
            }
        }
        return "Error,The recording file does not exist";
    }

    /**
     * 处理录音文件
     *
     * @param file 文件
     * @return 文字结果
     */
    private String processRecording(MultipartFile file) {
        // 处理录音文件,调用接口等逻辑

        // 返回文字结果
        return "Hello, this is the text result";
    }

}
最近下载更多
zhangdi11am  LV1 8月23日
最代码官方  LV168 2024年4月14日
最近浏览更多
zhangdi11am  LV1 8月23日
yuanshun  LV7 2024年11月18日
3993zby  LV2 2024年11月12日
shaohuaqingfu  LV3 2024年11月6日
charleswang  LV7 2024年10月21日
sky丶小十  LV7 2024年10月8日
zzzyyy1  LV2 2024年10月4日
Iterman  LV2 2024年9月30日
Peny_ZH  LV5 2024年9月21日
yimaoermao  LV1 2024年9月14日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友