I'm trying to report a bug of a MP3 decoder and the developer asked me to generate the PCM file for him to identify the problem.
So this is the code I used to generate the PCM file
private async Task NewMethod()
{
var file = await SelectPlaybackFile();
await Task.Run(() =>
{
_handle = Bass.BASS_StreamCreateFile(file.Path, 0,0,BASSFlag.BASS_STREAM_AUTOFREE | BASSFlag.BASS_SAMPLE_FLOAT);
var _myDSPProc = new DSPPROC(Dsp1);
int dspHandle = Bass.BASS_ChannelSetDSP(_handle, _myDSPProc, IntPtr.Zero, 0);
Bass.BASS_ChannelPlay(_handle, false);
});
}
unsafe void Dsp1(int handle, int channel, IntPtr buffer, int length, IntPtr user)
{
}
I notice the buffer is a unmanaged memory and I never dealt with it before. So I started doing some research and found a answer here and this is the code from that answer
private void callback(IntPtr buffer, int length)
{
FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);
int written;
WriteFile(file.Handle, buffer, length, out written, IntPtr.Zero);
file.Close();
}
[DllImport("kernel32.dll")]
private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int NumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);
However, the code above might not be working on UWP since the app is running in a sandbox and dev cannot access to path.
Is there any other way to help write a IntPtr to a file in UWP?
In UWP app you can access certain file system locations by default see the File access permissions document.
You can try the following code.
private async void Method(IntPtr buffer, int length)
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowReadersAndWriters);
unsafe
{
UnmanagedMemoryStream ustream = new UnmanagedMemoryStream((byte*)buffer, length);
ustream.CopyTo(stream.AsStream());
ustream.Dispose();
stream.Dispose();
}
}
Note: in Visual Studio, you should select the Allow unsafe code configuration.(Right click your project=>Select Build tab=>Select Allow unsafe code).