多次播放资源文件中WAV音频时出现"Wav header corrupt"错误求助
解决WAV文件首次播放正常、后续播放报"The wav header is corrupt"的问题
这个问题的核心是资源中的WAV文件是以UnmanagedMemoryStream形式存储的,第一次播放后,流的读取指针会移动到末尾,后续再调用播放时,程序从流的末尾开始读取,自然读不到正确的WAV头,就会抛出"头损坏"的错误。
以下是三种可行的解决办法:
方案1:每次播放前重置流的位置
如果deathSound是从资源中获取的UnmanagedMemoryStream,在播放前手动把流的Position设为0,让读取指针回到开头:
If enemy1.Bounds.IntersectsWith(sten.Bounds) Then If enemy1alive = 1 Then ' 重置流位置到开头 deathSound.Position = 0 My.Computer.Audio.Play(deathSound, AudioPlayMode.Background) End If enemy1alive = 0 enemy1.Location = enemy1spawn enemy1.Enabled = False enemy1.Visible = False score = score + 1 kills = kills + 1 kastad = 0 sten.Location = weaponPosition sten.Left = chunkymonkey.Left runTimer1.Stop() stentimer1.Stop() End If
方案2:将WAV转为Byte数组,每次播放创建新流
把资源中的WAV转成Byte数组存储,每次播放时基于数组创建新的MemoryStream,这样每次都是全新的流,不会有指针位置问题:
' 先在类级别定义Byte数组存储音频 Private deathSoundBytes As Byte() = My.Resources.DeathSound ' 替换成你的资源名 ' 播放逻辑里 If enemy1.Bounds.IntersectsWith(sten.Bounds) Then If enemy1alive = 1 Then Using ms As New MemoryStream(deathSoundBytes) My.Computer.Audio.Play(ms, AudioPlayMode.Background) End Using End If enemy1alive = 0 enemy1.Location = enemy1spawn enemy1.Enabled = False enemy1.Visible = False score = score + 1 kills = kills + 1 kastad = 0 sten.Location = weaponPosition sten.Left = chunkymonkey.Left runTimer1.Stop() stentimer1.Stop() End If
方案3:使用SoundPlayer类(更稳定)
SoundPlayer类专门处理WAV播放,内部会自动管理流的状态,比My.Computer.Audio更可靠:
' 类级别定义SoundPlayer实例 Private deathPlayer As New SoundPlayer(My.Resources.DeathSound) ' 替换成你的资源名 ' 播放逻辑里 If enemy1.Bounds.IntersectsWith(sten.Bounds) Then If enemy1alive = 1 Then deathPlayer.Play() ' 后台播放,对应AudioPlayMode.Background ' 如果需要同步播放用deathPlayer.PlaySync() End If enemy1alive = 0 enemy1.Location = enemy1spawn enemy1.Enabled = False enemy1.Visible = False score = score + 1 kills = kills + 1 kastad = 0 sten.Location = weaponPosition sten.Left = chunkymonkey.Left runTimer1.Stop() stentimer1.Stop() End If
内容的提问来源于stack exchange,提问作者AMT Productions
相关产品推荐
相关产品推荐

