How to use LibvlcSharp on Linux? - linux

I'm trying to use LibvlcSharp on a linux installation (Ubuntu 18.04). I'm following all the instructions, including this one Getting started on LibVLCSharp.Gtk for Linux but my application always crash. It's working perfectly on windows, because there we can add VideoLAN.LibVLC.Windows package, but I couldn't find someting similar for Linux.
My code:
static void Main(string[] args)
{
// Record in a file "record.ts" located in the bin folder next to the app
var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var destination = Path.Combine(currentDirectory, "record.ts");
// Load native libvlc library
Core.Initialize();
using (var libvlc = new LibVLC())
//var libvlc = "/usr/lib/x86_64-linux-gnu/";
using (var mediaPlayer = new MediaPlayer(libvlc))
{
// Redirect log output to the console
libvlc.Log += (sender, e) => Console.WriteLine($"[{e.Level}] {e.Module}:{e.Message}");
// Create new media with HLS link
var urlRadio = "http://transamerica.crossradio.com.br:9126/live.mp3";
var media = new Media(libvlc, urlRadio, FromType.FromLocation);
// Define stream output options.
// In this case stream to a file with the given path and play locally the stream while streaming it.
media.AddOption(":sout=#file{dst=" + destination + "}");
media.AddOption(":sout-keep");
// Start recording
mediaPlayer.Play(media);
Console.WriteLine($"Recording in {destination}");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
The error message:
Unhandled Exception: LibVLCSharp.Shared.VLCException: Failed to perform instanciation on the native side. Make sure you installed the correct VideoLAN.LibVLC.[YourPlatform] package in your platform specific project
at LibVLCSharp.Shared.Internal..ctor(Func1 create, Action1 release)
at RadioRecorderLibVlcSharp.Program.Main(String[] args) in /media/RadioRecorderLibVlcSharp/Program.cs:line 19
Anyone can help me?
thanks

Can you try apt-get install vlc? That seems to help getting all the required plugins/deps on your system (though it will pull vlc 2.x from the official ubuntu rep probably).

Related

Azure Batch with C# Application using System.Diagnostics.Process

I am using Azure Batch with a C# application. The overall C# application is responsible for doing many things. Unfortunately, 1 operation that works on my local machine does not work within an Azure Batch application.
The operation that works locally but not as an Azure C# application is programmatically starting a System.Diagnostics. A process that executes a FFmpeg argument to take a screenshot of a video. The process seems to run, but, the jpg file is not created. Locally, the code will create a jpg but as an Azure Batch app, the file is not created.
I have set the image file to be created in the AZ_BATCH_TASK_WORKING_DIR folder. I have reduced the code to just do the 1 operation that does not work as an Azure application and here it is:
using System;
using System.Diagnostics;
using System.IO;
namespace BatchAppWithFfmpegProcess
{
internal class Program
{
static void Main(string[] args)
{
#if DEBUG
string workingDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
#else
/*
Within each Tasks directory, the Batch service creates a working directory (wd) whose unique path is
specified by the AZ_BATCH_TASK_WORKING_DIR environment variable. This directory provides read/write access
to the task. The task can create, read, update, and delete files under this directory.
This directory is retained based on the RetentionTime constraint that is specified for the task.
The stdout.txt and stderr.txt files are written to the Tasks folder during the execution of the task.
*/
string workingDirectory = Environment.GetEnvironmentVariable("AZ_BATCH_TASK_WORKING_DIR");
#endif
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string ffmpegPath = Path.Combine(applicationPath, #"lib\");
string videoFilePath = Path.Combine(applicationPath, "MichaelJacksonSmoothCriminal_Trimmed.mp4");
string thumbnailFilePath = Path.Combine(workingDirectory, "MichaelJacksonSmoothCriminal_Trimmed.jpg");
if (File.Exists(thumbnailFilePath))
{
File.Delete(thumbnailFilePath);
}
string arguments = $"-i \"{videoFilePath}\" -ss 00:00:01.000 -frames:v 1 \"{thumbnailFilePath}\"";
var startInfo = new ProcessStartInfo
{
FileName = ffmpegPath + $"\\ffmpeg.exe",
Arguments = arguments,
RedirectStandardError = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = ffmpegPath
};
using (var process = new Process { StartInfo = startInfo })
{
process.Start();
process.WaitForExit();
}
if (File.Exists(thumbnailFilePath))
{
Console.WriteLine("Hurray, it worked!!!");
}
else
{
Console.WriteLine("File was not created.");
}
}
}
}
Perhaps it is impossible to use System.Diagnostics.Process to create files? I have tried to make this as easy as possible to reproduce with the following:
clone the code at:
https://github.com/Dapp3rDanH/AzBatchFfmpegProcess.git
Using Visual Studio 2022, "Publish" BatchAppWithFfmpegProcess code to a Folder using
"Deployment mode" = Self-Contained
Target Framework of net5.0
Target runtime = win-x64.
Create a BatchAppWithFfmpegProcess.zip zip file of the publish folder. Make sure the BatchAppWithFfmpegProcess.exe is in the root of the zip.
Create a Batch account.
Add a Batch application using the BatchAppWithFfmpegProcess.zip file with appId of BatchAppWithFfmpegProcess and a version of 1.
Add a Pool called "Pool1" with 1 dedicated node using microsoftwindowsserver windowsserver 2022-datacenter-core (latest). Add BatchAppWithFfmpegProcess version 1 to Pool1.
Create a new Job with a Task with the command of:
cmd /c %AZ_BATCH_APP_PACKAGE_BatchAppWithFfmpegProcess#1%\BatchAppWithFfmpegProcess.exe
If you check out the stdout.txt file of the task, you will see "File was not created". Any way to get this to work?
Thanks!
Dan
The issue was related to my pool being based upon "microsoftwindowsserver windowsserver 2022-datacenter-core (latest)".
Switching to microsoftwindowsserver windowsserver 2016-datacenter (latest) fixed the issue.

unity udp dgram socket not working on hololens

I tried to connect between hololens and python server. So I used dgram socket but this is not working on hololens.
this is my code sample.
hololens client
public string conHost = "192.168.0.58";
public int conPort = 3174;
void Start()
{
ipep = new IPEndPoint(IPAddress.Parse(conHost), conPort);
clientThread = new Thread(setupSocket);
clientThread.Start();
}
public void setupSocket()
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
void Update()
{
if(Send)
{
Send = false;
byte[] bytes = Encoding.UTF8.GetBytes("124306324602435");
byte[] buffer = Encoding.UTF8.GetBytes(bytes.Length.ToString());
mySocket.SendTo(buffer, buffer.Length, SocketFlags.None, ipep);
}
}
python server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#server_address = "192.168.0.18", 9029
#print('starting up on {} port {}'.format(*server_address))
sock.bind(("192.168.0.58", 3174))
ready=True
while(ready):
try:
epoch_time = time.time()
data,address = sock.recvfrom(100)
fileLength = data.decode("utf-8")
print(fileLength)
except:
continue
When I play this code in unity project, it works. But in hololens, not working.
I used try-catch, I got this error messege on Update
System.NullReferenceException: Object reference not set to an instance of an object [0x00000] in <000000000000000000000000000000000>:0
It occurs because the variable mySocket is not initialized as an expected value. Actually, the implementation of System.Threading has changed in .NET 4.x in a way that is not backward compatible, and the HoloLens app uses IL2CPP scripting backend with.NET4.x but the Unity Editor uses Mono scripting backend with.NET2.x. So, it works in Unity Editor but fails to start your thread in .NET4.x, we recommended that using System.Threading.Tasks class instead. Besides, to use WinRT APIs in Unity projects built for the UWP you need to use preprocessor directives, more information please see:WinRT APIs with Unity for HoloLens

How can I get information about the file that launched my app?

Similar to How to get the arguments for opening file with electron app but the solution there is not working for me.
Using:
OS - Windows 10
Electron - https://github.com/castlabs/electron-releases.git#v1.8.7-vmp1010
electron-builde - v20.28.3
I have a an electron app build with electron-builder, and using the latter I have specified a custom file association, .custom.
So when you double-click on a file with this extension, file.custom, the installed app opens. This file would have some data in it that the app needs, and I'd like to read this data using my app.
Is there any way that my app can detect what launched it, so that I can say "file.custom" launched me, and it's sitting at "C:\Users\Owner\Downloads\,?
The file does not appear in process.argv
You can get a reference to the file using process.argv, example:
var ipc = require('ipc');
var fs = require('fs');
// read the file and send data to the render process
ipc.on('get-file-data', function(event) {
var data = null;
if (process.platform == 'win32' && process.argv.length >= 2) {
var openFilePath = process.argv[1];
data = fs.readFileSync(openFilePath, 'utf-8');
}
event.returnValue = data;
});
source: Source

intel XDK directory browsing

I'm trying to get a way to reach and parse all JSON file from a directory, witch inside an Intel Xdk project. All files in my case stored in '/cards' folder of the project.
I have tried to reach theme with fs.readdirSync('/cards') method, but that wasn't pointed to the location what I expected, and I haven't got luck with 'intel.xdk.webRoot' path.
With the simulator I've managed to get files, with a trick:
fs.readdirSync(intel.xdk.webRoot.replace('localhost:53862/http-services/emulator-webserver/ripple/userapp/', '')+'cards');
(intel.xdk.webRoot contains absolute path to my '/cards' folder)
and its work like a charm, but it isn't working in any real device what I'd like to build it.
I have tried it with iOS7 and Android 4.2 phones.
Please help me to use in a great way the fs.readdirSync() method, or give me some alternate solution.
Thanks and regards,
satire
You can't use nodejs api's on mobile apps. It is a bug that the XDK emulator lets you do it. The bug is fixed in the next release of XDK.
You could write a node program that scans the directory and then writes out a js file with the contents of the directory. You would run the node script on your laptop before packaging the app in the build tab. The output would look like this:
files.js:
dir = {files: ['file1.txt', 'file2.txt']}
Then use a script tag to load it:
And your js can read the dir variable. This assumes that the contents does not change while the app is running.
The location of your application's root directory will vary depending on the target platform and can also vary with the emulator and the debug containers (e.g., App Preview versus App Analyzer). Here's what I've done to locate files within the project:
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}
I have not been able to test this exhaustively, but it appears to be working so far. Here's an example where I'm using a Cordova media object and want it to play a file stored locally in the project. Note that I have to "special case" the iOS container:
var x = window.device && window.device.platform ;
console.log("platform = ", x) ;
if(x.match(/(ios)|(iphone)|(ipod)|(ipad)/ig)) {
var media = new Media("audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
else {
var media = new Media(getWebRoot() + "/audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
console.log("media.src = ", media.src) ;
media.play() ;
Not quite sure if this is what you are looking for...
You will need to use the Cordova build in the Intel XDK, here is information on building with Cordova:
https://software.intel.com/en-us/html5/articles/using-the-cordova-for-android-ios-etc-build-option
And a DirectoryReader example:
function success(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
}
}
function fail(error) {
alert("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);

Playing wav/mp3 from Windows 7 service

I need to play a sound file (wav or mp3 is fine) from a service in Windows 7/2008... the way we did it in WinXP doesn't work anymore. I've followed this question Play wave file from a Windows Service (C#) with no success, in various combinations. The sound plays fine through the debugger but once I install it as a service it doesn't play, and event logs prove the call is being made. I've also followed the http://bresleveloper.blogspot.co.il/2012/06/c-service-play-sound-with-naudio.html link with the same result.
Code snippet follows below. It is a C# service with VS 2010, .Net 4.0, NAudio 1.5.4.0. I am using
InstallUtil to install/remove the service.
WRT the code, I comment out the Wav or MP3 stuff and one of the methods each time... they all play the sound sucessfully.
static class Program
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
static void Main(string[] args)
{
m_eventLog = new EventLog();
m_eventLog.Source = "EventLoggerSource";
if(args.Length > 0 && args[0].ToLower() == "/console")
{
AllocConsole();
EventLoggerApp app = new EventLoggerApp();
app.Start();
m_eventLog.WriteEntry("INFO (Calling Player)");
string fileFullPath=#"c:\aaasound\bunny_troubles.wav",fileFullPath2=#"c:\aaasound\dreams.mp3";
// Wav file
IWavePlayer wavePlayer=new WaveOutEvent(); // Method 1
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,false,100); // Method 2
AudioFileReader audioFile=new AudioFileReader(fileFullPath);
audioFile.Volume = (float)1.0;
wavePlayer.Init(audioFile);
// MP3 file
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,true,100); // Method 1- EventSync/not both work
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Exclusive,false,100); // Method 2- EventSync must be false or throws an exception
WaveStream mp3Reader = new Mp3FileReader(fileFullPath2);
WaveChannel32 inputStream=new WaveChannel32(mp3Reader);
WaveStream wavStream=new WaveChannel32(inputStream);
wavePlayer.Init(wavStream);
//this.wavePlayer.PlaybackStopped += new EventHandler(wavePlayer_PlaybackStopped);
wavePlayer.Play();
while(wavePlayer.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(100);
}

Resources