| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import express from 'express';
- import multer from 'multer';
- import path from 'path';
- import os from 'os';
- import fs from 'fs';
- import { IflytekAsr } from './iflytek.js';
- const router = express.Router();
- const asr = new IflytekAsr({
- appId: '783cfeb8',
- accessKeyId: '5d58267f04be61379a33cf74744377d6',
- apiSecret: 'YTBkZGIyMTk2MDYyOGIyYTQzNTEwZjZm',
- host: 'https://office-api-ist-dx.iflyaisol.com',
- });
- const upload = multer({
- dest: path.join(os.tmpdir(), 'asr-uploads'),
- limits: { fileSize: 500 * 1024 * 1024 },
- });
- // POST /api/asr/transcribe — 上传音频 → 创建转写任务
- router.post('/transcribe', upload.single('audio'), async (req, res) => {
- try {
- const file = req.file;
- if (!file) {
- return res.status(400).json({ success: false, error: '请上传音频文件' });
- }
- const audioBuffer = fs.readFileSync(file.path);
- const language = req.body.language || 'autodialect';
- const orderId = await asr.createTask({
- audio: audioBuffer,
- fileName: file.originalname || 'audio.wav',
- language,
- });
- fs.unlink(file.path, () => {});
- res.json({ success: true, data: { orderId, fileName: file.originalname, size: file.size } });
- } catch (e: any) {
- if (req.file) fs.unlink(req.file.path, () => {});
- res.status(500).json({ success: false, error: e.message });
- }
- });
- // POST /api/asr/transcribe-base64 — base64 上传
- router.post('/transcribe-base64', async (req, res) => {
- try {
- const { audio, fileName, language } = req.body;
- if (!audio) {
- return res.status(400).json({ success: false, error: '缺少 base64 音频数据' });
- }
- const audioBuffer = Buffer.from(audio, 'base64');
- const orderId = await asr.createTask({
- audio: audioBuffer,
- fileName: fileName || 'audio.wav',
- language: language || 'autodialect',
- });
- res.json({ success: true, data: { orderId } });
- } catch (e: any) {
- res.status(500).json({ success: false, error: e.message });
- }
- });
- // GET /api/asr/result/:orderId — 查询转写结果
- router.get('/result/:orderId', async (req, res) => {
- try {
- const result = await asr.getResult(req.params.orderId);
- res.json({ success: true, data: result });
- } catch (e: any) {
- res.status(500).json({ success: false, error: e.message });
- }
- });
- export default router;
|