Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a File Descriptor Handle from FileStream

Tags:

c#

mono

monomac

I'm using this library https://github.com/ahawker/NLibsndfile for convert audio files with libSndFile from C#, i did this method, for the conversion (coverts wav to 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);

The problem is at time to open the aiff file, the method api.OpenFileDescriptor always return an null pointer. The library method is this: internal static extern IntPtr sf_open_fd(int handle, LibsndfileMode mode, ref LibsndfileInfo info, int closeHandle);

Any idea why is failing the operation? or how to get the file Descriptor Handler from FileStream?

like image 709
GustavoTM Avatar asked Mar 27 '13 21:03

GustavoTM


Video Answer


1 Answers

You can get the descriptor like so:

First use FileStream.SafeFileHandle and use the value of that to access SafeHandle.DangerousGetHandle()

So: IntPtr handle = fileStream.SafeFileHandle.DangerousGetHandle();

like image 121
Matthew Watson Avatar answered Sep 21 '22 16:09

Matthew Watson