默认音频改成随机从mp3目录取

This commit is contained in:
jianzhichu
2026-01-14 17:13:15 +08:00
parent 1f96f31c69
commit 8da82889d1
2 changed files with 128 additions and 109 deletions
+96 -96
View File
@@ -28,16 +28,16 @@ namespace dy.net.Controllers
private readonly DouyinFollowService douyinFollowService; private readonly DouyinFollowService douyinFollowService;
private readonly DouyinCookieService douyinCookieService; private readonly DouyinCookieService douyinCookieService;
// 定义允许上传的音频扩展名(小写) //// 定义允许上传的音频扩展名(小写)
private readonly string[] _allowedAudioExtensions = { ".mp3", ".wav" }; //private readonly string[] _allowedAudioExtensions = { ".mp3", ".wav" };
// 定义允许的音频 MIME 类型(增强验证) //// 定义允许的音频 MIME 类型(增强验证)
private readonly string[] _allowedAudioMimeTypes = { //private readonly string[] _allowedAudioMimeTypes = {
"audio/mpeg", "audio/wav" // "audio/mpeg", "audio/wav"
}; //};
// 最大文件大小:20MB(可根据需求调整) // 最大文件大小:20MB(可根据需求调整)
private const long _maxFileSize = 20 * 1024 * 1024; //private const long _maxFileSize = 20 * 1024 * 1024;
public ConfigController(DouyinCookieService dyCookieService, DouyinCommonService commonService, DouyinQuartzJobService quartzJobService, DouyinFollowService douyinFollowService, DouyinCookieService douyinCookieService) public ConfigController(DouyinCookieService dyCookieService, DouyinCommonService commonService, DouyinQuartzJobService quartzJobService, DouyinFollowService douyinFollowService, DouyinCookieService douyinCookieService)
@@ -388,106 +388,106 @@ namespace dy.net.Controllers
} }
/// <summary> ///// <summary>
/// 上传音频文件接口 ///// 上传音频文件接口
/// </summary> ///// </summary>
/// <param name="file">要上传的音频文件</param> ///// <param name="file">要上传的音频文件</param>
/// <returns>上传结果</returns> ///// <returns>上传结果</returns>
[HttpPost("UploadAudio")] //[HttpPost("UploadAudio")]
public IActionResult UploadAudio(IFormFile file) //public IActionResult UploadAudio(IFormFile file)
{ //{
// 1. 验证文件是否为空 // // 1. 验证文件是否为空
if (file == null || file.Length == 0) // if (file == null || file.Length == 0)
{ // {
return BadRequest(new { success = false, message = "请选择要上传的音频文件" }); // return BadRequest(new { success = false, message = "请选择要上传的音频文件" });
} // }
try // try
{ // {
// 2. 验证文件大小 // // 2. 验证文件大小
if (file.Length > _maxFileSize) // if (file.Length > _maxFileSize)
{ // {
return BadRequest(new { success = false, message = $"文件大小超过限制(最大允许 {_maxFileSize / 1024 / 1024}MB" }); // return BadRequest(new { success = false, message = $"文件大小超过限制(最大允许 {_maxFileSize / 1024 / 1024}MB" });
} // }
// 3. 获取文件扩展名并验证 // // 3. 获取文件扩展名并验证
var fileExtension = Path.GetExtension(file.FileName).ToLower(); // var fileExtension = Path.GetExtension(file.FileName).ToLower();
if (!_allowedAudioExtensions.Contains(fileExtension)) // if (!_allowedAudioExtensions.Contains(fileExtension))
{ // {
return BadRequest(new // return BadRequest(new
{ // {
success = false, // success = false,
message = $"不支持的音频格式,仅允许:{string.Join(", ", _allowedAudioExtensions)}" // message = $"不支持的音频格式,仅允许:{string.Join(", ", _allowedAudioExtensions)}"
}); // });
} // }
// 4. 验证 MIME 类型(可选但推荐,防止扩展名伪造) // // 4. 验证 MIME 类型(可选但推荐,防止扩展名伪造)
var contentType = file.ContentType.ToLower(); // var contentType = file.ContentType.ToLower();
if (!_allowedAudioMimeTypes.Contains(contentType)) // if (!_allowedAudioMimeTypes.Contains(contentType))
{ // {
return BadRequest(new // return BadRequest(new
{ // {
success = false, // success = false,
message = "文件类型验证失败,请上传合法的音频文件" // message = "文件类型验证失败,请上传合法的音频文件"
}); // });
} // }
//先删除 // //先删除
var uploadMp3 = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3")) // var uploadMp3 = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3"))
.Where(filePath => Path.GetFileNameWithoutExtension(filePath) != "silent_10") // .Where(filePath => Path.GetFileNameWithoutExtension(filePath) != "silent_10")
.FirstOrDefault(); // .FirstOrDefault();
if (!string.IsNullOrWhiteSpace(uploadMp3) && System.IO.File.Exists(uploadMp3)) // if (!string.IsNullOrWhiteSpace(uploadMp3) && System.IO.File.Exists(uploadMp3))
{ // {
System.IO.File.Delete(uploadMp3); // System.IO.File.Delete(uploadMp3);
} // }
// 5. 生成唯一文件名(避免重复) // // 5. 生成唯一文件名(避免重复)
var uniqueFileName = $"dysync_default{fileExtension}"; // var uniqueFileName = $"dysync_default{fileExtension}";
// 6. 定义文件保存路径(建议配置在 appsettings.json 中,这里简化处理) // // 6. 定义文件保存路径(建议配置在 appsettings.json 中,这里简化处理)
var uploadPath = Path.Combine(AppContext.BaseDirectory, "mp3"); // var uploadPath = Path.Combine(AppContext.BaseDirectory, "mp3");
// 确保目录存在 // // 确保目录存在
if (!Directory.Exists(uploadPath)) // if (!Directory.Exists(uploadPath))
{ // {
Directory.CreateDirectory(uploadPath); // Directory.CreateDirectory(uploadPath);
} // }
// 7. 保存文件 // // 7. 保存文件
var filePath = Path.Combine(uploadPath, uniqueFileName); // var filePath = Path.Combine(uploadPath, uniqueFileName);
if (System.IO.File.Exists(filePath)) // if (System.IO.File.Exists(filePath))
{ // {
System.IO.File.Delete(filePath); // System.IO.File.Delete(filePath);
} // }
using (var stream = new FileStream(filePath, FileMode.Create)) // using (var stream = new FileStream(filePath, FileMode.Create))
{ // {
file.CopyTo(stream); // file.CopyTo(stream);
} // }
// 8. 返回成功结果(可根据需求返回文件路径/URL 等) // // 8. 返回成功结果(可根据需求返回文件路径/URL 等)
return ApiResult.Success(new { fileName = uniqueFileName, filePath }); // return ApiResult.Success(new { fileName = uniqueFileName, filePath });
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
// 捕获异常并返回错误信息 // // 捕获异常并返回错误信息
return ApiResult.Fail(ex.Message); // return ApiResult.Fail(ex.Message);
} // }
} //}
[AllowAnonymous] //[AllowAnonymous]
[HttpGet("defaudio")] //[HttpGet("defaudio")]
public async Task<IActionResult> GetDefaultAudioUrl() //public async Task<IActionResult> GetDefaultAudioUrl()
{ //{
var uploadMp3 = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3")) // var uploadMp3 = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3"))
.Where(filePath => Path.GetFileNameWithoutExtension(filePath) != "silent_10") // .Where(filePath => Path.GetFileNameWithoutExtension(filePath) != "silent_10")
.FirstOrDefault(); // .FirstOrDefault();
if (!string.IsNullOrWhiteSpace(uploadMp3) && System.IO.File.Exists(uploadMp3)) // if (!string.IsNullOrWhiteSpace(uploadMp3) && System.IO.File.Exists(uploadMp3))
{ // {
return File(System.IO.File.ReadAllBytes(uploadMp3), "application/octet-stream", Path.GetFileName(uploadMp3)); // return File(System.IO.File.ReadAllBytes(uploadMp3), "application/octet-stream", Path.GetFileName(uploadMp3));
} // }
return ApiResult.Fail("未上传音频"); // return ApiResult.Fail("未上传音频");
} //}
} }
} }
+32 -13
View File
@@ -2,6 +2,8 @@
using dy.net.dto; using dy.net.dto;
using dy.net.utils; using dy.net.utils;
using Serilog; using Serilog;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace dy.net.service namespace dy.net.service
{ {
@@ -44,34 +46,51 @@ namespace dy.net.service
int width = 1080, int width = 1080,
int height = 1920) int height = 1920)
{ {
string mp3FilePath = GetDefaultAudio(); string mergMusicPath = GetRandomMergeMusic();
if (!string.IsNullOrWhiteSpace(audioPath)) if (!string.IsNullOrWhiteSpace(audioPath))
{ {
var (SuccessPaths, _) = await DownloadMediaAsync(new List<string> { audioPath }, Path.GetDirectoryName(savePath), "audio_", "mp3", ck); var (SuccessPaths, _) = await DownloadMediaAsync(new List<string> { audioPath }, Path.GetDirectoryName(savePath), "audio_", "mp3", ck);
if (SuccessPaths != null && SuccessPaths.Length > 0) if (SuccessPaths != null && SuccessPaths.Length > 0)
{ {
mp3FilePath = SuccessPaths[0]; mergMusicPath = SuccessPaths[0];
} }
} }
var ffmpeg = new FFmpegHelper(); var ffmpeg = new FFmpegHelper();
return await ffmpeg.MergeMultipleVideosAsync(videoFilePaths, mp3FilePath, savePath, width, height); return await ffmpeg.MergeMultipleVideosAsync(videoFilePaths, mergMusicPath, savePath, width, height);
} }
private static string GetDefaultAudio() private static string GetRandomMergeMusic()
{ {
string mp3FilePath = Path.Combine(AppContext.BaseDirectory, "mp3", "silent_10.mp3"); var allowedExtensions = new HashSet<string> { ".mp3", ".wav" };
var uploadMp3 = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3")) string mergMusic = Path.Combine(AppContext.BaseDirectory, "mp3", "silent_10.mp3");//默认音频
.Where(filePath => Path.GetFileNameWithoutExtension(filePath) != "silent_10") var customMusics = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "mp3"))
.FirstOrDefault(); .Where(filePath =>
if (!string.IsNullOrWhiteSpace(uploadMp3) && File.Exists(uploadMp3)) allowedExtensions.Contains(Path.GetExtension(filePath).ToLowerInvariant()) &&
Path.GetFileNameWithoutExtension(filePath) != "silent_10")
.ToList();
if (customMusics != null && customMusics.Any())
{ {
mp3FilePath = uploadMp3; if (customMusics.Count() == 1)
return customMusics.FirstOrDefault();
// 使用加密级别的随机数生成器(RNGCryptoServiceProvider)获取高随机性的索引
using (var rng = RandomNumberGenerator.Create())
{
byte[] randomNumber = new byte[4];
rng.GetBytes(randomNumber);
// 将随机字节转换为非负整数,并取模得到有效索引
int randomIndex = Math.Abs(BitConverter.ToInt32(randomNumber, 0)) % customMusics.Count();
return customMusics.ToList()[randomIndex];
}
} }
return mp3FilePath; return mergMusic;
} }
@@ -171,8 +190,8 @@ namespace dy.net.service
if (rawAudios.Length == 0) if (rawAudios.Length == 0)
{ {
var mp3Path = GetDefaultAudio(); var musicPath = GetRandomMergeMusic();
rawAudios = new string[] { mp3Path }; rawAudios = new string[] { musicPath };
Log.Debug("版权原因无法下载音频,使用默认无声音频文件"); Log.Debug("版权原因无法下载音频,使用默认无声音频文件");
} }