2

我正在用 C#/MonoGame 编写一个 libretro 前端,我已经设法获得了一个粗糙(但有效)的视频 blitter,但现在我正在努力解决声音问题。

从 API:

/* Renders multiple audio frames in one go.
 *
 * One frame is defined as a sample of left and right channels, interleaved.
 * I.e. int16_t buf[4] = { l, r, l, r }; would be 2 frames.
 * Only one of the audio callbacks must ever be used.
 */
typedef size_t (*retro_audio_sample_batch_t)(const int16_t *data,
      size_t frames);

因此,样本是有符号的 16 位整数。我正在尝试像这样使用 Stream 中的 SoundEffect:

        int size = SoundEffect.GetSampleSizeInBytes(TimeSpan.FromMilliseconds((float)1000/(int)_libretro.GetAVInfo().timing.fps), (int)_libretro.GetAVInfo().timing.sample_rate, AudioChannels.Mono);           
        data = _libretro.GetSoundBuffer().data;

        byte[] buffer = new byte[size];
        for (int i = 0; i < size -1 ; i+=2)
        {
            Int16 chunk = Marshal.ReadInt16(data);

            byte b1 = (byte)(chunk);
            byte b2 = (byte)(chunk >> 8);
            buffer[i+1] = b1;
            buffer[i] = b2;

            //move ahead 4 bytes skipping the second sound channel for now
            data = data + (sizeof(byte)*4);
        }

        SoundEffect sound_left = new SoundEffect(buffer, (int)_libretro.GetAVInfo().timing.sample_rate, AudioChannels.Mono);
        sound_left.Play();

我得到了声音,声音模式清晰可辨,但它是乱码,你看到我的实现有什么问题吗?

4

2 回答 2

3

此方法会将样本数据转换为字节数组。它适用于任何通道数(在单声道和立体声上测试)。

    public static byte[] GetSamplesWaveData(float[] samples, int samplesCount)
    {
        var pcm = new byte[samplesCount * 2];
        int sampleIndex = 0,
            pcmIndex = 0;

        while (sampleIndex < samplesCount)
        {
            var outsample = (short)(samples[sampleIndex] * short.MaxValue);
            pcm[pcmIndex] = (byte)(outsample & 0xff);
            pcm[pcmIndex + 1] = (byte)((outsample >> 8) & 0xff);

            sampleIndex++;
            pcmIndex += 2;
        }

        return pcm;
    }

请注意,这些float[] samples值应在范围内[-1;1]

于 2017-02-10T05:13:59.117 回答
1

我实际上并不确定,但是既然你得到了 b1 和 b2,并且你使用了两次 b1,也许你只是错误地写了 b1 而不是 b2:

byte b1 =(byte)(chunk);
byte b2 = (byte)(chunk << 8);
buffer[i] = b1;//thats b1
buffer[i+1] = b1;//thats b1 again

也许你需要类似的东西:

buffer[i+1] = b2;

但我不确定你想在那里做什么,所以我不知道我的回答是否有任何相关性。

更新现在我认为我明白了,您正在将 16bit-int 转换为几个字节。所以正确的语法是:

byte b1 =(byte)(chunk);
byte b2 = (byte)(chunk >> 8); 

因为谈话总是最不重要的部分,所以你需要把它撕碎。

于 2015-08-12T06:16:29.660 回答