routes.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import express from 'express';
  2. import multer from 'multer';
  3. import path from 'path';
  4. import os from 'os';
  5. import fs from 'fs';
  6. import { IflytekAsr } from './iflytek.js';
  7. const router = express.Router();
  8. const asr = new IflytekAsr({
  9. appId: '783cfeb8',
  10. accessKeyId: '5d58267f04be61379a33cf74744377d6',
  11. apiSecret: 'YTBkZGIyMTk2MDYyOGIyYTQzNTEwZjZm',
  12. host: 'https://office-api-ist-dx.iflyaisol.com',
  13. });
  14. const upload = multer({
  15. dest: path.join(os.tmpdir(), 'asr-uploads'),
  16. limits: { fileSize: 500 * 1024 * 1024 },
  17. });
  18. // POST /api/asr/transcribe — 上传音频 → 创建转写任务
  19. router.post('/transcribe', upload.single('audio'), async (req, res) => {
  20. try {
  21. const file = req.file;
  22. if (!file) {
  23. return res.status(400).json({ success: false, error: '请上传音频文件' });
  24. }
  25. const audioBuffer = fs.readFileSync(file.path);
  26. const language = req.body.language || 'autodialect';
  27. const orderId = await asr.createTask({
  28. audio: audioBuffer,
  29. fileName: file.originalname || 'audio.wav',
  30. language,
  31. });
  32. fs.unlink(file.path, () => {});
  33. res.json({ success: true, data: { orderId, fileName: file.originalname, size: file.size } });
  34. } catch (e: any) {
  35. if (req.file) fs.unlink(req.file.path, () => {});
  36. res.status(500).json({ success: false, error: e.message });
  37. }
  38. });
  39. // POST /api/asr/transcribe-base64 — base64 上传
  40. router.post('/transcribe-base64', async (req, res) => {
  41. try {
  42. const { audio, fileName, language } = req.body;
  43. if (!audio) {
  44. return res.status(400).json({ success: false, error: '缺少 base64 音频数据' });
  45. }
  46. const audioBuffer = Buffer.from(audio, 'base64');
  47. const orderId = await asr.createTask({
  48. audio: audioBuffer,
  49. fileName: fileName || 'audio.wav',
  50. language: language || 'autodialect',
  51. });
  52. res.json({ success: true, data: { orderId } });
  53. } catch (e: any) {
  54. res.status(500).json({ success: false, error: e.message });
  55. }
  56. });
  57. // GET /api/asr/result/:orderId — 查询转写结果
  58. router.get('/result/:orderId', async (req, res) => {
  59. try {
  60. const result = await asr.getResult(req.params.orderId);
  61. res.json({ success: true, data: result });
  62. } catch (e: any) {
  63. res.status(500).json({ success: false, error: e.message });
  64. }
  65. });
  66. export default router;