从FileStream获取文件描述符句柄

时间:2013-03-27 21:15:35

标签: c# mono monomac

我正在使用这个库https://github.com/ahawker/NLibsndfile来转换来自C#的libSndFile的音频文件,我做了这个方法,用于转换(转换为wav到aiff):

        string sourcePath = "/User/Dev/Desktop/a.wav";
        string targetPath = "/User/Dev/Desktop/b.aiff";

        var file = File.Create(targetPath);
        file.Close();
        file.Dispose();
        IntPtr ptrTargetFile = file.SafeFileHandle.DangerousGetHandle();

        LibsndfileInfo wavInfo = new LibsndfileInfo();
        LibsndfileInfo aiffInfo = new LibsndfileInfo();
        LibsndfileApi api = new LibsndfileApi();

        var wavFile = api.Open(sourcePath, LibsndfileMode.Read, ref wavInfo);
        var aiffFile = api.OpenFileDescriptor((int)ptrTargetFile, LibsndfileMode.Rdwr, ref aiffInfo, 0);

        aiffInfo.Channels = wavInfo.Channels;
        aiffInfo.SampleRate = wavInfo.SampleRate;
        aiffInfo.Format = LibsndfileFormat.Aiff;

        short[] buffer = new short[512];

        long countOfItemsWritten = 0;
        long countOfItemsReaded = 0;

        while ((countOfItemsReaded=api.ReadItems(wavFile, buffer, buffer.Length))>0)
            countOfItemsWritten = api.WriteItems(aiffFile, buffer, countOfItemsReaded);

        api.Close(wavFile);
        api.Close(aiffFile);

问题在于打开aiff文件,方法api.OpenFileDescriptor总是返回空指针。库方法是:internal static extern IntPtr sf_open_fd(int handle, LibsndfileMode mode, ref LibsndfileInfo info, int closeHandle);

知道为什么操作失败?或者如何从FileStream获取Descriptor Handler文件?

1 个答案:

答案 0 :(得分:4)

您可以像这样获取描述符:

首先使用FileStream.SafeFileHandle并使用其值来访问SafeHandle.DangerousGetHandle()

所以:IntPtr handle = fileStream.SafeFileHandle.DangerousGetHandle();