Skip to content

Commit

Permalink
Fix SoundPlayer handling of partial reads on streams
Browse files Browse the repository at this point in the history
SoundPlayer assumes that a Read on a stream will return everything asked for, and that's not the case.
  • Loading branch information
stephentoub committed Feb 24, 2023
1 parent 5415cd1 commit 216778b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,20 @@ private void LoadStream(bool loadSync)
int streamLen = (int)_stream.Length;
_currentPos = 0;
_streamData = new byte[streamLen];
_stream.Read(_streamData, 0, streamLen);
#if NET7_0_OR_GREATER
_stream.ReadExactly(_streamData);
#else
int totalRead = 0;
while (totalRead < streamLen)
{
int bytesRead = _stream.Read(_streamData, totalRead, streamLen - totalRead);
if (bytesRead <= 0)
{
throw new EndOfStreamException();
}
totalRead += bytesRead;
}
#endif
IsLoadCompleted = true;
OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,22 @@ public void PlayLooping_NullStream_Success()
player.PlayLooping();
}

[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[MemberData(nameof(Play_String_TestData))]
[OuterLoop]
public void PlaySync_TrickledData_Success(string sourceLocation)
{
using var player = new SoundPlayer();
player.Stream = new TrickleStream(File.ReadAllBytes(sourceLocation.Replace("file://", "")));
player.PlaySync();
}

private sealed class TrickleStream : MemoryStream
{
public TrickleStream(byte[] bytes) : base(bytes) { }
public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, 1));
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsSoundPlaySupported))]
[OuterLoop]
public void PlaySync_NullStream_Success()
Expand Down

0 comments on commit 216778b

Please sign in to comment.