BackgroundAudioPlayer is 'Playing' but not calling GetSampleAsync()

﹥>﹥吖頭↗ 提交于 2019-12-04 15:47:25

ReportGetSampleCompleted once data is available is the correct approach in this scenario.

You will have to keep track in your MSS whether you need to report any new sample data immediately or wait for GetSampleAsync to be called.

However watch that failures due to race condition are possible between the various threads involved.

As it happens, a solution appears to be to break the contract suggested by the name GetSampleAsync, and block in that method when not enough data has been buffered. The stream callbacks can then pulse the locked object, and the sample read can be retried. Something like this works well:

private void OnMoreDataDownloaded(object sender, EventArgs e)
{
    // We're on an arbitrary thread, so instead of reporting
    // a sample here we should just pulse.
    lock (buffering_lock) {
        is_buffering = false;
        Monitor.Pulse(buffering_lock);
    }
}

protected override void GetSampleAsync()
{
    while (we_need_more_data) {
        lock (buffering_lock) {
            is_buffering = true;
            while (is_buffering) {
                Monitor.Wait(buffering_lock);
            }
    }

    // code code code
    ReportGetSampleCompleted(sample);
}

It would seem that blocking in an Async method might not be wise, but the experience of running this code on a device suggests otherwise. Per http://msdn.microsoft.com/en-us/library/system.windows.media.mediastreamsource.getsampleasync(v=vs.95).aspx, blocking could prevent other streams from being read. As a streaming music app, we only ever serve one stream at a time, so in this case it seems that we're OK.

I wish I knew a general solution here, though, because this clearly is cheating.

If you don't have any data available then fill a buffer with silence and report that. This will give you time for real data to come in.

You want to center the data to the middle of a PCM range on your silence data or you'll get a click when going silent.

MemoryStream stream = new MemoryStream();

byte[] silenceBuffer = BitConverter.GetBytes( (ushort)(short.MaxValue) );
for(int i=0; i < 1000; i++ )
    stream.Write( silenceBuffer, 0, silenceBuffer.Length );

Gook luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!