"My First BASS Application" BASS.NET application error - c#

I am trying to create an application with audio from the BASS.NET Library, but I am getting a few errors on the "My First BASS Application" sample. I followed the given directions on http://bass.radio42.com/help/, but when I try running the pasted code, an error comes up on this line:
if ( Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero) )
the error I recieve is:
An unhandled exception of type 'System.TypeInitializationException' occurred in Bass Test.exe
I tried to follow all the directions, but for #4, instead of adding bass.dll, I added bass.net.dll thinking it was typo.
4.Copy the 'bass.dll' to your executable directory (e.g. .\bin\Debug).
The sample code is:
using System;
using Un4seen.Bass;
namespace MyFirstBass
{
class Program
{
static void Main(string[] args)
{
// init BASS using the default output device
if (Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero))
{
// create a stream channel from a file
int stream = Bass.BASS_StreamCreateFile("test.mp3", 0, 0, BASSFlag.BASS_DEFAULT);
if (stream != 0)
{
// play the stream channel
Bass.BASS_ChannelPlay(stream, false);
}
else
{
// error creating the stream
Console.WriteLine("Stream error: {0}", Bass.BASS_ErrorGetCode());
}
// wait for a key
Console.WriteLine("Press any key to exit");
Console.ReadKey(false);
// free the stream
Bass.BASS_StreamFree(stream);
// free BASS
Bass.BASS_Free();
}
}
}
}
I am guessing that the code is fine but my computer's output device is whats causing the error.

BASS.NET is a thin wrapper over BASS, which means bass.dll is required. The link you provided explicitly warns:
The native BASS libraries are NOT included and need to be downloaded separately - so make sure to place the BASS library and the needed add-on libraries to your project executable directory (e.g. place the bass.dll to your .\bin\Debug folder).
You don't need to copy bass.net.dll to the Debug folder yourself because you've already added it as a reference to your project.

Related

Read audio file duration in C# on Linux with .net 6

I have an asp.net core API that was recently updated from .net5 to .net6.
There is a piece of code that should read a duration of an audio file. The code that seems to have worked on previous versions was this:
try
{
//
// NAudio -- Windows only
//
using var fileReader = new AudioFileReader(filePath);
return Convert.ToInt32(Math.Ceiling(fileReader.TotalTime.TotalSeconds));
}
catch (DllNotFoundException)
{
try
{
//
// LibVLCSharp is crossplatform
//
using var libVLC = new LibVLC();
using var media = new Media(libVLC, filePath, FromType.FromPath);
MediaParsedStatus parsed = Task.Run(async () => await media.Parse(MediaParseOptions.ParseNetwork, timeout: 2000).ConfigureAwait(false)).Result;
if (parsed != MediaParsedStatus.Done) throw new ArgumentException("Could not read audio file");
if (!media.Tracks.Any(t => t.TrackType == TrackType.Audio) || (media.Duration <= 100)) throw new ArgumentException("Could not read audio from file");
return Convert.ToInt32(Math.Ceiling(TimeSpan.FromMilliseconds(media.Duration).TotalSeconds));
}
catch (Exception ex) when (ex is DllNotFoundException || ex is LibVLCSharp.Shared.VLCException)
{
try
{
using var fileReader = new Mp3FileReader(filePath);
return Convert.ToInt32(Math.Ceiling(fileReader.TotalTime.TotalSeconds));
}
catch (InvalidOperationException)
{
throw new ArgumentException("Could not read audio file");
}
}
}
The application was deployed on Linux and, I don't know which part of the code did the exact calculation (I am assuming the VLC part), but since the update to .NET6, all of these fail, and since the last fallback is NAudio, we get the following exception:
Unable to load shared library 'Msacm32.dll' or one of its dependencies.
I am using Windows, but I tried running the app with WSL, and I can't get the VLC part to run either - it always throws the following exception (even after installing vlc and vlc dev SDK):
LibVLC could not be created. Make sure that you have done the following:
Installed latest LibVLC from nuget for your target platform.
Unable to load shared library 'libX11' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibX11: cannot open shared object file: No such file or directory at LibVLCSharp.Shared.Core.Native.XInitThreads()
at LibVLCSharp.Shared.Core.InitializeDesktop(String libvlcDirectoryPath)
at LibVLCSharp.Shared.Helpers.MarshalUtils.CreateWithOptions(String[] options, Func`3 create)
Is there any clean way to read a duration of an audio file on all platforms?
Needless to say, NAudio works like a charm on Windows, and so does the VLC (with the proper nuget package).
If you install ffmpeg, you can do this quite easily. ffmpeg comes installed in most linux distros by default, but in case it isn't, you can install it with your favorite package manager.
sudo apt install ffmpeg
To install it in windows, you'll need to download the build files, extract it, and add it to the PATH.
Next, install Xabe.FFMpeg package in your project.
Finally, you can call the static method Xabe.FFMpeg.FFMpeg.GetMediaInfo() to get all information regarding your audio file. Here is a sample snippet that I tested on my linux machine.
using System;
using System.IO;
using Xabe.FFmpeg;
namespace Program;
public static class Program
{
public static void Main(string[] args)
{
string filename;
if (args.Length == 0)
{
Console.WriteLine("No arguments found! Provide the audio file path as argument!");
return;
}
else if (File.Exists(filename = args[0]) == false)
{
Console.WriteLine("Given file does not exist!");
return;
}
try
{
var info = FFmpeg.GetMediaInfo(filename).Result;
TimeSpan duration = info.Duration;
Console.WriteLine($"Audio file duration is {duration}");
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
}
The error you are seeing is because we were assuming that you would display a video on linux, using X11, so we are always initializing X11. See here.
We shouldn't do that for your use case(because you may not have a GUI available). Please report the issue here : https://code.videolan.org/videolan/LibVLCSharp/-/issues
or even better, submit a pull request on github or gitlab.
As for your question of why did it work on .net 5 and not anymore, I'm not sure we have enough info to tell why, because you didn't send us the error message from that machine.
I would encourage you to take a look at atldotnet. It is a small, well maintained completely managed code / cross platform library without any external dependencies and was accurate detecting audio file duration in all of my test cases (more accurate than ffmpeg). Most common audio formats are supported.
var t = new Track(audioFilePath);
// Works the same way on any supported format (MP3, FLAC, WMA, SPC...)
System.Console.WriteLine("Duration (ms) : " + t.DurationMs);

Darkflow frozen pb - tensorflowsharp output

I am having some problem with my object detection project. I have a working solution that uses tensorflowsharp nuget. I am trying to get faster detection and I wanted to experiment with YOLO model.
I am using darkflow for having YOLO working with Tensorflow. I trained my model on my custom dataset and then I froze it using the instruction on the darkflow page. I now have my PB file and a metafile, so far so good.
I then adjusted my code in the tensorflowsharp project, pointing to the just created protobuf and adapted the name of the input output variables, from:
String[] outputs = { "detection_boxes:0", "detection_scores:0", "detection_classes:0", "num_detections:0" };
runner.AddInput("image_tensor:0", tensor).Fetch(outputs);
try
{
output = runner.Run();
}
catch (TFException e)
{
Console.WriteLine(e.ToString());
}
to:
runner.AddInput("input:0", tensor).Fetch("output:0");
try
{
output = runner.Run();
}
catch (TFException e)
{
Console.WriteLine(e.ToString());
}
Following the name of the variables in the darkflow documentation. I am able to add input and output pointer to the session but when I get to run the detection (Runner.Run) I get an exception:
TensorFlow.TFException: Expects arg[0] to be float but uint8 is provided
Runner.Run() returns null.
I am not sure what the name of the output tensors are in darkflow, on the documentation I found:
The name of input tensor and output tensor are respectively 'input' and 'output'. For further usage of this protobuf file, please refer to the official documentation of Tensorflow on C++ API here.
but I would expect different collection (tensors) as return type as it is for SSD and other models, right?

IMAPI: COMException Internal file system error occurred [-1062555360 ]

I am writing CD/DVD using IMAPI with C#.NET windows application.
The data I write on CD contains one executable file (test.exe) which is also developed with C#.NET and virtualized (sandobx) using Turbo Virtualization Studio.
All data to be written on CD is placed in one folder (source path) on C drive.
Following is small code snippet: -
IStream stream = null;
try
{
System.Diagnostics.Debug.Print("Adding - " + thisFileItem.SourcePath);
if (thisFileItem.SourcePath != null)
Win32.SHCreateStreamOnFile(thisFileItem.SourcePath, Win32.STGM_READ | Win32.STGM_SHARE_DENY_WRITE, ref stream);
if (stream != null)
{
fileSystemImage.Root.AddFile(thisFileItem.DestPath + thisFileItem.DisplayName, stream);
}
}
finally
{
if (stream != null)
{
Marshal.FinalReleaseComObject(stream);
}
}
Call to "fileSystemImage.Root.AddFile" method while adding test.exe throws COMException -1062555360 "Internal file system error occurred." All other files add and write properly.
Exception Details: -
COMException -1062555360
Internal file system error occurred.
at ImapiInterop.IFsiDirectoryItem.AddFile(String path, IStream fileData)
at ImapiImplementation.CDWriter.objBackgroundWorker_DoWork(Object sender, DoWorkEventArgs e) in C:\.........\CDWriter.cs:line 405
If I put my source folder on some other location (Desktop or D drive), all writing process (including test.exe) happens fine without error.
I suspect the issue is due to virutalization but not sure.
Please help.
The error message returned by IMAPI is incorrect and that is why all confusion.
Refer following link.
social.msdn.microsoft.com
Following is the text copied from answer (from Dmitri) on above site: -
IMAPI supports the ISupportErrorInfo interface, and we are aware of
the issue of mismatching error messages in your scenario.
Internally, IMAPI creates rollback objects to undo add/remove file
actions. We've had an issue where the rollback action was created
prematurely, so after the return code for IFsiDirectoryItem::AddFile
was already set, the rollback action was to remove the file from the
image. Since the file hasn't been added, IMAPI_E_FSI_INTERNAL_ERROR
exception was thrown, which changed the IErrorInfo message to the one
you're seeing.
We are aware of this issue, and it will be fixed in the next release
of IMAPI. Unfortunately, it is not serious enough to be addressed in a
hotfix.

IVsDropdownBarClient and GetEntryText: Problems with text buffers

In my Visual Studio extension, I'm going to read the text that is in the navigation bar. Therefore I listen to window created events and from the IVsCodeWindow object I get the IVsDropdownBar to get the current selection in the dropdown bar. This works fine. Then I'm using the following code snippet to extract the text of the current selection:
string text;
barClient.GetEntryText(MembersDropdown, curSelection, out text);
if (hr == VSConstants.S_OK)
{
Debug.WriteLine("Text: " + text);
} else {
Debug.WriteLine("No text found!");
}
However, this does not work. My extension crashes with an unhandled exception in the second line of the code snippet. I read the documentation and could find the following note:
The text buffer returned in ppszText is typically created by the
IVsDropdownBarClient object and the buffer must persist for the life
of the IVsDropdownBarClient object. If you are implementing this
interface in managed code and you need to have the string disposed of
by the caller, implement the IVsCoTaskMemFreeMyStrings interface on
the IVsDropdownBarClient interface.
I assume that this is part of my problem, but I can't really understand what I have to change in my code to get it working. Any hints?
I'm pretty sure now that the Visual Studio SDK Interop DLLs have the wrong marshalling information for IVsDropDownbarClient.GetEntryText and that there's no way to call that method using that interface.
The best workaround I've found so far is:
Use the tlbimp tool to generate an alternate Interop DLL for textmgr. (You can safely ignore the dozens of warnings including the one about GetTextEntry.)
tlbimp "c:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\VisualStudioIntegration\Common\Inc\textmgr.tlb"
(Optional) If you're using source control, you'll probably want to copy the resulting file (TextManagerInternal.dll) to a subdirectory of your extension project and check it in as an external dependency.
In your Visual Studio extension project, add a reference to the file (TextManagerInternal.dll).
Add the following method that should properly handle the string marshalling.
static public string HackHackGetEntryText(IVsDropdownBarClient client, int iCombo, int iIndex)
{
TextManagerInternal.IVsDropdownBarClient hackHackClient = (TextManagerInternal.IVsDropdownBarClient) client;
string szText = null;
IntPtr ppszText = IntPtr.Zero;
try
{
ppszText = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
if(ppszText == IntPtr.Zero)
throw new Exception("Unable to allocate memory for IVsDropDownBarClient.GetTextEntry string marshalling.");
hackHackClient.GetEntryText(iCombo, iIndex, ppszText);
IntPtr pszText = Marshal.ReadIntPtr(ppszText);
szText = Marshal.PtrToStringUni(pszText);
}
finally
{
if(ppszText != IntPtr.Zero)
Marshal.FreeCoTaskMem(ppszText);
}
return szText;
}
}

WMEncoder Throws COMException (0x80004005) Unspecified Error

So I'm running this code
public static void ConvertToWma(string inFile, string outFile, string profileName)
{
// Create a WMEncoder object.
WMEncoder encoder = new WMEncoder();
ManualResetEvent stopped = new ManualResetEvent(false);
encoder.OnStateChange += delegate(WMENC_ENCODER_STATE enumState)
{
if (enumState == WMENC_ENCODER_STATE.WMENC_ENCODER_STOPPED)
stopped.Set();
};
// Retrieve the source group collection.
IWMEncSourceGroupCollection srcGrpColl = encoder.SourceGroupCollection;
// Add a source group to the collection.
IWMEncSourceGroup srcGrp = srcGrpColl.Add("SG_1");
// Add an audio source to the source group.
IWMEncSource srcAud = srcGrp.AddSource(WMENC_SOURCE_TYPE.WMENC_AUDIO);
srcAud.SetInput(inFile, "", "");
// Specify a file object in which to save encoded content.
IWMEncFile file = encoder.File;
file.LocalFileName = outFile;
// Choose a profile from the collection.
IWMEncProfileCollection proColl = encoder.ProfileCollection;
proColl.ProfileDirectory = AssemblyInformation.GetExecutingAssemblyDirectory();
proColl.Refresh();
IWMEncProfile pro;
for (int i = 0; i < proColl.Count; i++)
{
pro = proColl.Item(i);
if (pro.Name == profileName)
{
srcGrp.set_Profile(pro);
break;
}
}
// Start the encoding process.
// Wait until the encoding process stops before exiting the application.
encoder.SynchronizeOperation = false;
encoder.PrepareToEncode(true);
encoder.Start();
stopped.WaitOne();
}
And I get a COMException (0x80004005) when encoder.PrepareToEncode gets executed.
Some notes:
1) The process is spawned by an ASP.NET web service so it runs as NETWORK SERVICE
2) inFile and outFile are absolute local paths and their extensions are correct, in addition inFile definitely exists (this has been a source of problems in the past)
3) The program works when I run it as myself but doesn't work in the ASP.NET context.
This says to me its a security permission issue so in addition I've granted Full Control to the directory containing the program AND the directories containing the audio files to NETWORK SERVICE. So I really don't have any idea what more I can do on the security front. Any help?
Running WM Encoder SDK based app in windows service is not supported. It uses hidden windows for various reasons, and there isn't a desktop window in service. DRM would certainly fail with no user profile. Besides, even when you make your service talk to WME instance on a user's desktop, Microsoft only supports 4 concurrent requests per machine because the global lock in WME (I know, not pretty programming, but WME is old). For more scalable solutions, consider Windows Media Format SDK.
You may want to move your WM Encoder based app to Expression Encoder SDK as WM Encoder's support is ending.

Categories

Resources