Play wav voice file in console program

本文介绍如何使用C++编程语言,通过简单的代码片段,实现播放本地wav音频文件的功能。利用PlaySound函数,轻松地将声音文件融入您的程序中。

First, you need prepare the wav voice file in the current folder, e.g., "door2.wav" here.

Then, just 1 line code needs:


#include <windows.h>
#include "tchar.h"

#pragma comment(lib, "winmm.lib")

int main()
{
    PlaySound( _T("door2.wav"), NULL, SND_SYNC);

    return 0;
}


using System.Speech.Synthesis; using System.Media; using System.Runtime.InteropServices; var builder = WebApplication.CreateBuilder(args); // 添加服务 builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new() { Title = "Text to Speech API with Broadcast", Version = "v1" }); }); // 注册音频播放服务 builder.Services.AddSingleton<IAudioPlayerService, AudioPlayerService>(); var app = builder.Build(); // 配置中间件 if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "TTS Broadcast API v1"); }); } app.UseStaticFiles(); app.UseRouting(); app.UseHttpsRedirection(); app.UseAuthorization(); // 创建输出目录 Directory.CreateDirectory("Output"); // TTS生成端点 app.MapPost("/tts", async (TtsRequest request, IAudioPlayerService audioService) => { // 1. 生成语音文件 var audioPath = Path.Combine("Output", $"{Guid.NewGuid()}.wav"); using (var synthesizer = new SpeechSynthesizer()) { foreach (var voice in synthesizer.GetInstalledVoices()) { Console.WriteLine($"Name: {voice.VoiceInfo.Name}, Culture: {voice.VoiceInfo.Culture}, Enabled: {voice.Enabled}"); } synthesizer.SetOutputToWaveFile(audioPath); //列出所有已安装的语音 var allVoices = synthesizer.GetInstalledVoices(); foreach (var voice in allVoices) { Console.WriteLine($"Voice: {voice.VoiceInfo.Name}, Culture: {voice.VoiceInfo.Culture}"); } // 设置语言 if (!string.IsNullOrEmpty(request.Language)) { try { var culture = new System.Globalization.CultureInfo(request.Language); var voices = synthesizer.GetInstalledVoices(culture) .Where(v => v.Enabled) .ToList(); if (voices.Any()) { synthesizer.SelectVoice(voices.First().VoiceInfo.Name); } else if (request.Language == "vi-VN") { // 特殊处理越南语 var vietnameseVoices = synthesizer.GetInstalledVoices() .Where(v => v.VoiceInfo.Name.Contains("An", StringComparison.OrdinalIgnoreCase)) .ToList(); if (vietnameseVoices.Any()) { synthesizer.SelectVoice(vietnameseVoices.First().VoiceInfo.Name); } } } catch { // 语言设置失败时使用默认语音 } } // 设置语速 if (request.Rate.HasValue) { synthesizer.Rate = Math.Clamp(request.Rate.Value, -10, 10); } synthesizer.Speak(request.Text); } // 2. 播放音频 audioService.SetVolume(request.Volume); audioService.Play(audioPath); // 3. 返回结果 return Results.Ok(new { message = "语音已生成并播放", audioFile = Path.GetFileName(audioPath), playStatus = "playing" }); }) .WithName("TextToSpeech") .Produces(200); // 文件访问端点 app.MapGet("/files/{filename}", (string filename) => { var filePath = Path.Combine("Output", filename); return File.Exists(filePath) ? Results.File(filePath) : Results.NotFound(); }); // 音频控制端点 app.MapPost("/audio/stop", (IAudioPlayerService audioService) => { audioService.Stop(); return Results.Ok(new { message = "播放已停止" }); }); app.MapPost("/audio/volume", (int level, IAudioPlayerService audioService) => { audioService.SetVolume(level); return Results.Ok(new { message = $"音量已设置为 {level}" }); }); // 根路径重定向到Swagger app.MapGet("/", () => Results.Redirect("/swagger")); app.Run(); // ========== 服务接口和实现 ========== public interface IAudioPlayerService { void Play(string filePath); void Stop(); void SetVolume(int volume); } public class AudioPlayerService : IAudioPlayerService { private SoundPlayer _player; private readonly object _lock = new object(); public void Play(string filePath) { lock (_lock) { Stop(); // 停止当前播放 _player = new SoundPlayer(filePath); _player.Play(); // 异步播放 Console.WriteLine($"[播放] {Path.GetFileName(filePath)}"); } } public void Stop() { lock (_lock) { if (_player != null) { _player.Stop(); _player.Dispose(); _player = null; Console.WriteLine("[停止] 播放已终止"); } } } public void SetVolume(int volume) { // 确保音量在0-100范围内 volume = Math.Clamp(volume, 0, 100); NativeMethods.SetVolume(volume); Console.WriteLine($"[音量] 设置为 {volume}%"); } } // ========== Windows API封装 ========== internal static class NativeMethods { [DllImport("winmm.dll")] private static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume); public static void SetVolume(int volume) { // 计算音量值 (0-65535) uint newVolume = (uint)((volume / 100.0) * 65535); // 设置左右声道相同音量 newVolume = (newVolume << 16) | newVolume; waveOutSetVolume(IntPtr.Zero, newVolume); } } // ========== 请求模型 ========== public record TtsRequest( string Text, string? Language = null, // 语言代码如 "zh-CN", "en-US" "vi_VN" int Volume = 80, // 音量 0-100 int? Rate = null // 语速 -10 到 10 );看下这段api代码 没有实现越南语 不知道是什么地方的问题 这个支持越南语吗 安装越南语包有没有脚本安装的
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值