依赖包
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="6.0.13" />
使用方式
注入 services.AddHttpClient<XunFeiAudioService>();
XunFeiAudioService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Tool.Services
{
public class XunFeiAudioService
{
private readonly string LFASR_HOST = "https://raasr.xfyun.cn/api";
/**
* TODO 设置appid和secret_key
*/
private readonly string APPID = "";
private readonly string SECRET_KEY = "";
private readonly string PREPARE = "/prepare";
private readonly string UPLOAD = "/upload";
private readonly string MERGE = "/merge";
private readonly string GET_PROGRESS = "/getProgress";
private readonly string GET_RESULT = "/getResult";
/**
* 文件分片大小,可根据实际情况调整
*/
private readonly static int SLICE_SICE = 10485760;// 10M
private readonly HttpClient _httpClient;
public XunFeiAudioService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string?> DoXunFeiAudioWork( string filePath)
{
string taskId = await Prepare(new FileInfo(filePath));
if (string.IsNullOrWhiteSpace(taskId))
{
return "分析失败";
}
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//剩余文件内容长度
byte[] buffer = new byte[SLICE_SICE];
List<byte[]> bytes = new List<byte[]>();
SliceIdGenerator generator = new SliceIdGenerator();
int length = 0;
//文件切块。
while ((length = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] buffer_copey = new byte[length];
if (length < buffer.Length)
{
buffer = buffer.Take(length).ToArray();
}
buffer.CopyTo(buffer_copey, 0);
bytes.Add(buffer_copey);
await UploadSlice(taskId, generator.getNextSliceId(), buffer_copey);
}
fileStream.Close();
// 合并文件
await Merge(taskId);
//轮询获取任务结果
while (true)
{
try
{
Console.WriteLine("sleep a while Zzz");
Thread.Sleep(20000);
}
catch (Exception e)
{
Console.WriteLine($"{e.Message}{e.StackTrace}");
}
XunFeiApiResult taskProgress = await GetProgress(taskId);
if (taskProgress.ok == 0)
{
if (taskProgress.err_no != 0)
{
//Console.WriteLine("任务失败:" + taskProgress.ToJsonString());
}
if (taskP