Playing wav/mp3 from Windows 7 service - c#-4.0

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);
}

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 to use LibvlcSharp on 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).

How to launch another Android app using cocos2d-x?

I'm making a game with cocos2d-x for Android using C++. Now I'm looking for a way to open another Android App (likes YouTube, Google Play Store, ...) using their package name from inside my game through a button . I have searched around and found that it could be done in Java code with something like this:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
My question is: Is it possible to open another Android App in my native code (.cpp files) or I have to put them in java side (.java files)? If I have to do it in .java files, where should I put it? I always work with .cpp files in Visual Studio, compile with cmd and run with emulator on Android Studio, I have never worked with .java files that generated by cocos2d-x in Android Studio, the engine just makes everything ready for me so I got a little confused here.
Update 1:
Abhishek Aryan's advice works but my Game crashed on resume when I'm in another App. I'm trying to performs some actions before opening others app and they might cause the crash because I could run it without any problem if I remove those action and leave openApp function alone.
My expect: Press the button => pause my game and open You Tube on Android => Press Back Button => pause You Tube and resume my game.
What happens: I could open You Tube but my App crashed when I press back button. I got the following error code from Android Studio:
A/libc: Fatal signal 11 (SIGSEGV) at 0x0004fb18 (code=1), thread 1975 (Thread-55)
Any idea how could I fix it?
My code :
auto imageOpeningAction = CallFunc::create([&]() {
mOpeningImage->setEnabled(true);
mOpeningImage->setOpacity(255);
mOpeningImage->setPosition(menuItem->getPosition());
mOpeningImage->runAction(fullScale);
});
auto imageClosingAction = CallFunc::create([&]() {
mOpeningImage->runAction(reverseScale);
mOpeningImage->setOpacity(0);
mOpeningImage->setEnabled(false);
});
auto openAnotherApp = CallFunc::create([&]() { // Open YouTube app
HelloWorld::openApp(packageName);
});
runAction(Sequence::create(imageOpeningAction->clone(), DelayTime::create(0.5f), openAnotherApp->clone(), nullptr));
Your attention and help is very much appreciated.
You need to use JNI for your requirement.
Create a method that open any app in your AppActivity.
public class AppActivity extends Cocos2dxActivity {
private static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity=this;
}
public static void openOtherApp(String packageName){
Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
if (launchIntent != null) {
activity.startActivity(launchIntent);
}
}
}
Done !
Not yet, now only I need to call openOtherApp method from c++ so I create a method in my .cpp file.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#endif
void openApp(std::string packageName){
#if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
JniMethodInfo methodInfo;
const char* class_name="org/cocos2dx/cpp/AppActivity";
const char* method_name="openOtherApp";
const char* parameter= "(Ljava/lang/String;)V";
if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, class_name, method_name ,parameter )) {
return;
}
jstring jStringParam = methodInfo.env->NewStringUTF(packageName.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID,jStringParam);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
#endif
}
Want to open facebook call openApp(com.facebook.katana);

Pubnub library not compiling on Particle Photon

I am trying to publish a message using pubnub on the Particle Photon. The code snippet below comes straight out of the Pubnub example code.
The code will not compile, with the message from the compiler as follows:
PubNub/PubNub.h:87:47: error: expected class-name before '{' token
class PubSubClient: public PubNub_BASE_CLIENT {
^
PubNub/PubNub.h: In constructor 'PubSubClient::PubSubClient()':
PubNub/PubNub.h:23:28: error: class 'PubSubClient' does not have any field named 'WiFiClient'
#define PubNub_BASE_CLIENT WiFiClient
^
The code for this tiny project is as follows:
// This #include statement was automatically added by the Particle IDE.
#include "PubNub/PubNub.h"
char pubkey[] = "<key here>";
char subkey[] = "<key here>";
char channel[] = "Channel";
void setup() {
Serial.begin(9600);
Particle.publish("Serial set up");
PubNub.begin(pubkey, subkey);
}
void loop() {
TCPClient *client;
char msg[64] = "{\"photon\":\"on\"}";
client = PubNub.publish(channel, msg);
client->stop();
Delay (30000);
}
Has anyone had a similar problem, and if so, can you guide me as to how to fix this.
Thanks.
It looks like the library available in Build IDE was in an older version (0.0.1). Fixed, latest version (0.0.2) has been published.
To update library in your app you need to remove the PubNub library from your app in Apps drawer:
And then go to Libraries drawer, find PubNub library, click Include in App, select your app and confirm:

Resources