73 lines
2.3 KiB
C#
73 lines
2.3 KiB
C#
namespace ShengShengBuXi.ConsoleApp.Services;
|
|
|
|
/// <summary>
|
|
/// 音频文件服务实现
|
|
/// </summary>
|
|
public class AudioFileService : IAudioFileService
|
|
{
|
|
private readonly SemaphoreSlim _fileLock = new(1, 1);
|
|
|
|
/// <summary>
|
|
/// 更新音频文件
|
|
/// </summary>
|
|
/// <param name="fileName">文件名</param>
|
|
/// <param name="fileData">文件数据</param>
|
|
public async Task UpdateAudioFileAsync(string fileName, byte[] fileData)
|
|
{
|
|
if (string.IsNullOrEmpty(fileName) || fileData == null || fileData.Length == 0)
|
|
{
|
|
Console.WriteLine("音频文件名为空或文件数据为空");
|
|
return;
|
|
}
|
|
|
|
// 获取文件的完整路径
|
|
string filePath = Path.Combine(
|
|
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mp3"),
|
|
fileName);
|
|
|
|
await _fileLock.WaitAsync();
|
|
try
|
|
{
|
|
// 确保目录存在
|
|
string directory = Path.GetDirectoryName(filePath) ?? string.Empty;
|
|
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
|
{
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
// 写入文件
|
|
await File.WriteAllBytesAsync(filePath, fileData);
|
|
Console.WriteLine($"已更新音频文件: {fileName}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"更新音频文件失败: {ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
_fileLock.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 确保音频文件目录存在
|
|
/// </summary>
|
|
/// <param name="basePath">基础路径</param>
|
|
public void EnsureAudioDirectoryExists(string basePath)
|
|
{
|
|
string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, basePath);
|
|
if (!Directory.Exists(fullPath))
|
|
{
|
|
try
|
|
{
|
|
Directory.CreateDirectory(fullPath);
|
|
Console.WriteLine($"已创建音频目录: {fullPath}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"创建音频目录失败: {ex.Message}");
|
|
throw new DirectoryNotFoundException($"无法创建音频目录: {fullPath}", ex);
|
|
}
|
|
}
|
|
}
|
|
} |