You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将byte[]音频转换为string?解决.NET WinForms播放循环音频报错

解决Windows Forms中SoundPlayer加载嵌入音频的类型错误

问题原因

当WAV音频作为嵌入资源添加到项目中时,Properties.Resources.Anty返回的是byte[]类型数据,而你调用的SoundPlayer(string)构造函数需要传入文件路径字符串,因此触发类型转换错误。

修正方案

将byte[]包装为MemoryStream,使用SoundPlayer支持的Stream构造函数来加载音频:

  1. 确保代码文件顶部引入System.IO命名空间
  2. 修改代码如下:
new Thread(() =>
{
    using (var audioStream = new MemoryStream(Properties.Resources.Anty))
    {
        SoundPlayer player = new SoundPlayer(audioStream);
        player.PlayLooping();
    }
}).Start();

关键说明

  • MemoryStream把字节数组转换为SoundPlayer可识别的流格式,匹配对应的构造函数
  • using语句会自动释放MemoryStream资源,避免内存泄漏
  • 补充调用Start()启动线程,原代码缺少此步骤会导致音频无法播放

内容的提问来源于stack exchange,提问作者Sebastian Kavci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 17:43:15