我有一小段代码可以通过 Tao.Sdl 播放音调。它在 Linux 和 Mac 上运行良好(使用 Mono),但它在 Windows7、64 位的 Mono 或 .NET 上崩溃。这是代码:
using System;
using System.Runtime.InteropServices;
using Tao.Sdl;
namespace ConsoleApplication1
{
class Program
{
delegate void AudioSpecCallbackDelegate(IntPtr userData, IntPtr stream, int length);
static Sdl.SDL_AudioSpec desired;
static IntPtr specPtr;
static IntPtr obtained;
static void Main(string[] args)
{
Sdl.SDL_Init(Sdl.SDL_INIT_AUDIO);
desired = new Sdl.SDL_AudioSpec();
desired.freq = 22050;
desired.format = (short)Sdl.AUDIO_S16LSB;
desired.channels = 1;
desired.samples = (short)1000; //(short)2205;
desired.callback = Marshal.GetFunctionPointerForDelegate((AudioSpecCallbackDelegate)DoCallback);
desired.userdata = null;
specPtr = Marshal.AllocHGlobal(Marshal.SizeOf(desired));
Marshal.StructureToPtr(desired, specPtr, false);
obtained = IntPtr.Zero;
if (Sdl.SDL_OpenAudio((IntPtr)specPtr, (IntPtr)obtained) < 0)
{
Console.WriteLine("Error opening sdl_audio (1)");
Console.WriteLine(Sdl.SDL_GetError());
}
Sdl.SDL_PauseAudio(0);
Sdl.SDL_Delay(1000);
Sdl.SDL_PauseAudio(1);
}
public static void DoCallback(IntPtr userData, IntPtr stream, int len)
{
Console.WriteLine("{0}, ", len);
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++)
buffer[i] = 0;
Marshal.Copy(buffer, 0, stream, len);
}
}
}
它第二次尝试调用回调时在 Windows 上崩溃。你能看出我做错了什么吗?也许我没有正确的频率值,或者格式在 Windows 上很重要?
或者,我不知道如何调试低级代码......它只是在 Visual Studio 或 MonoDevelop 中崩溃。或者,如果您有关于使用不同系统重新执行此代码的建议。目标:能够在 Mac、Windows 和 Linux 上用 C# 处理要通过声音系统播放的字节。