How To Play A Beep/Alert Sound On Mac In Java - java

I have tried using both
Toolkit.getDefaultToolkit().beep(); and
System.out.println("\007");
and neither are actually playing a sound. I tried running the code in my IDE (CodeRunner 2) and in Terminal to see if it made a difference, which it didn't.
If anyone know another way to do this or why it isn't working, please let me know
Thanks!

Or you might try to use it with JNA-Library:
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.Native;
import com.sun.jna.Library;
interface JnaTests extends Library {
public boolean Beep(int FREQUENCY , int DURATION );
static Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
static void startBeep() throws InterruptedException {
kernel32.Beep(1200, (5000));
Thread.sleep(50);
}
}
package com.sun.jna.platform;
import com.sun.jna.Library;
public class win32 {
private static class MSG implements User32 {
public MSG() {
}
}
public interface Kernel32 extends Library { // ... (lines deleted for clarity) ...
boolean Beep(int frequency, int duration);
//int GetLogicalDrives(); // ... (lines deleted for clarity) ... }
}
public interface User32 extends Library { // ... (lines deleted for clarity) ...
// ... (lines deleted for clarity) ... }
}
}
Perhaps you could use the midi class too:
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Sequence sequence = new Sequence(Sequence.PPQ,4);
Track track = sequence.createTrack();
ShortMessage a = new ShortMessage();
a.setMessage(144,9,56,100);
MidiEvent event = new MidiEvent(a, 1);
track.add(event);
sequencer.setSequence(sequence);
sequencer.start();
Thread.sleep(500);
sequencer.close();

I think you are looking for Runtime#exec(String):
Runtime.getRuntime().exec(cmd);
This should allow you to get an instance of the current environment in which you can issue such commands.

Related

Bukkit Register Commands in Runtime

I am trying to register a bukkit Command on the other Command.
So I want to make "/command1" to register "/command2" so command 2 only can execute after I executed command 1.
I tried for like 10 hours by now to do that, at the moment I am able to register a command without making it into the plugin.yml and that works, just the second command does not get registered.
Main class:
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
public class Main extends JavaPlugin {
#Getter
CommandMap commandMap;
#Override
public void onEnable() {
loadCommandMap();
this.commandMap.register("command1", new FirstCommand(this));
}
private void loadCommandMap() {
try {
if (Bukkit.getPluginManager() instanceof SimplePluginManager) {
Field f = SimplePluginManager.class.getDeclaredField("commandMap");
f.setAccessible(true);
this.commandMap = (CommandMap) f.get(Bukkit.getPluginManager());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
FirstCommand:
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class FirstCommand extends Command {
private Main plugin;
public FirstCommand(Main plugin) {
super("command1");
this.plugin = plugin;
}
#Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
plugin.getCommandMap().register("command2", new SecondCommand());
sender.sendMessage("Command 1.");
return true;
}
}
Second Command:
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class SecondCommand extends Command {
public SecondCommand() {
super("command2");
}
#Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
sender.sendMessage("Command 2");
return true;
}
}
I really hope someone knows why the first command gets registered but the second one does not.
You could try to not register them at runtime, but enable them at runtime.
You can use global, static variables (for example in the main class of your app), e.g.
// in your class "Main"
public static boolean isCommand2Enabled = false;
and when command1 is called, you set it to true
Main.isCommand2Enabled = true;
Your command2 must now only check whether it has already been activated and can be executed:
if(!Main.isCommand2Enabled) {
// I am not activated yet and must return
return false;
}
But I am not quite sure if you might try to define the name of command2 first when command1 is executed (variable command name). You should then maybe use a fixed command and only make the corresponding argument variable.
I don't really understand what you are talking about, but I think this may help you...
Bukkit Tutorial - Registering Commands At Runtime

Stop JavaCV playback warning

Problem:
Receiving a stream of command line warnings as video plays - deprecated pixel format used, make sure you did set range correctly
Question:
How can I stop the warnings from happening or being displayed?
Update - Fixed:
The solution was too override the logging callback and don't do anything in the logging call method. FFmpeg logging is then disabled.
The reason for the message from FFmpeg is because it is grabbing frames from an old video format so is unavoidable if playing older videos.
NOTE:
This solution completely disables all output from FFmpeg. Even FFmpeg errors are muted.
Code below (just frame grabbing, not timed playback).
package test.javacv;
import java.io.File;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.CustomLogCallback;
public class TestPlay implements Runnable {
private static String video_loc = null;
private static CanvasFrame canvas = new CanvasFrame("Test JavaCV player");
public static void main(String[] args) { new Thread(new TestPlay(args[0])).start(); }
static {
CustomLogCallback.set();
}
public void run() { play_video(video_loc); }
public TestPlay(String loc) {
video_loc = loc;
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public static final void play_video(String vid_loc) {
try {
File file = new File(vid_loc);
FFmpegFrameGrabber ffmpeg_fg = new FFmpegFrameGrabber(file.getAbsolutePath());
Frame frm;
ffmpeg_fg.setAudioChannels(0);
ffmpeg_fg.start();
for(;;)
if((frm = ffmpeg_fg.grab()) != null) canvas.showImage(frm);
else {
ffmpeg_fg.setTimestamp(0);
break;
}
ffmpeg_fg.stop();
} catch(Exception ex) { ex("play_video vid_loc:" + vid_loc, ex); }
}
public static final void ex(String txt, Exception ex) {
System.out.println("EXCEPTION: " + txt + " stack..."); ex.printStackTrace(System.out); }
}
Logging class
// custom logger to override all logging output
package org.bytedeco.javacv;
import org.bytedeco.javacpp.BytePointer;
import static org.bytedeco.javacpp.avutil.LogCallback;
import static org.bytedeco.javacpp.avutil.setLogCallback;
public class CustomLogCallback extends LogCallback {
static final CustomLogCallback instance = new CustomLogCallback();
public static CustomLogCallback getInstance() { return instance; }
public static void set() { setLogCallback(getInstance()); }
#Override
public void call(int level, BytePointer msg) {}
}
You can adjust the logging level in JavaCV using org.bytedeco.javacpp.avutil.av_log_set_level().
calling avutil.av_log_set_level(avutil.AV_LOG_QUIET); will probably get you what you want.

JNA: Missing some specifics methods

I'm wanting create a dll injector in Java ( and only in Java ) for educational proporses for myself and found a basic example in a website especialized in online game.
The autor only said that was made using JNA interface.
So, i'm studyng this piece of code and trying compile with success using NetBeans IDE and JNA, but seem that JNA interface that i have here ( 4.2.2 ) not have all methods and functions used on piece of code left by autor.
Are they:
GetProcAddress
VirtualAllocEx
VirtualFreeEx
So, i'm wanting some help here if possible, for try solved this trouble of missing of methods in JNA.
I had fixed big part these erros but still missing some methods in JNA like i will show following point to point with comments.
package inject;
//////////////////// JNA-4.2.2 /////////////////////
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import java.io.File;
//////////////////////////////////////////////////
// Extracted from: https://github.com/warmuuh/AndroidCtx/tree/master/HotContext/src/luz/winapi
import inject.luz.winapi.constants.DwDesiredAccess;
import inject.luz.winapi.tools.Advapi32Tools;
import inject.luz.winapi.tools.Kernel32Tools;
import luz.winapi.api.exception.Kernel32Exception;
//////////////////////////////////////////////////////////////////////////////////////////////
public class Inject {
private static int GetPid(String proc){
int id = 0;
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (Native.toString(processEntry.szExeFile).equalsIgnoreCase(proc)) {
id = processEntry.th32ProcessID.intValue();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return id;
}
private static String findProcessByPID(int pid){
String name = "";
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (pid == processEntry.th32ProcessID.intValue()) {
name = processEntry.szExeFile.toString();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return name;
}
public static void inject(File dll, Integer pId) throws Kernel32Exception {
if(null == dll || !dll.exists() || !dll.isFile() || !dll.getName().endsWith(".dll"))
return;
String p = findProcessByPID(pId);
if(null == p) return;
Kernel32 kernel = Kernel32.INSTANCE;
HMODULE kernel32Pointer = kernel.GetModuleHandle("Kernel32");
// Cannot find "GetProcAddress"
Pointer loadLibraryAddress = kernel.GetProcAddress(kernel32Pointer, "LoadLibraryA");
HANDLE process = null;
DwDesiredAccess access = new DwDesiredAccess();
access.setPROCESS_ALL_ACCESS();
try {
Advapi32Tools.getInstance().enableDebugPrivilege(Kernel32Tools.getInstance().GetCurrentProcess());
} catch (Exception e) {
}
// Incompatible types "Pointer" and "HANDLE"
process = Kernel32Tools.getInstance().OpenProcess(access, false, pId);
String path = dll.getPath() + '\0';
byte[] bytes = path.getBytes();
int pathLength = bytes.length;
// Cannot find "VirtualAllocEx"
Pointer memoryDllPath = kernel.VirtualAllocEx(process, null, pathLength, Kernel32Tools.MEM_COMMIT, Kernel32Tools.PAGE_READWRITE);
Memory dllPathContent = new Memory(pathLength);
for(int i=0;i<pathLength;i++)
dllPathContent.setByte(i, bytes[i]);
IntByReference writeResult = new IntByReference();
boolean successWritting = kernel.WriteProcessMemory(process, memoryDllPath, dllPathContent, pathLength, writeResult);
if(!successWritting) {
kernel.CloseHandle(process);
return;
}
IntByReference threadId = new IntByReference();
// Pointer cannot be converted to "FOREIGN_THREAD_START_ROUTINE"
Pointer thread = kernel.CreateRemoteThread(process, null, 0, loadLibraryAddress, memoryDllPath, 0, threadId);
boolean res = false;
// Incompatible types "Pointer" and "HANDLE" //Cannot find "WAIT_TIMEOUT"
res = kernel.WaitForSingleObject(thread, Integer.MAX_VALUE) != Kernel32Tools.WAIT_TIMEOUT;
// Cannot find "VirtualFreeEx" method // Cannot find "MEM_RELEASE"
kernel.VirtualFreeEx(process, memoryDllPath, pathLength, Kernel32Tools.MEM_RELEASE);
kernel.CloseHandle(process);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(GetPid("notepad.exe"));
}
}
Thank in advance by any suggestion or help :-)
JNA missing methods? It ain't so!
You just need to extend the library and add your own (and, ideally, also contribute the "missing" methods back to the JNA library so others can benefit.
Here is an example of how someone has mapped GetProcAddress.
Someone has mapped VirtualAllocEx here (although they should properly have extended Kernel32 rather than copied it entirely and edited portions)
I couldn't find an example of VirtualFreeEx within the same 15 seconds I found the others... doesn't mean it's not out there but after writing the others you shouldn't have much trouble writing it as well.

Cannot change boolean value in method

I've got a little problem. I'm playing mp3 using Java sound sampled and I want to stop playing when I click the button. So I came up with something like this:
package sk.umb.osadnici.Client.Core.getterImages;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.FloatControl;
import javazoom.jl.player.advanced.AdvancedPlayer;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class GetterForBGMusic {
private SourceDataLine line;
private URL url;
public URL bgUrl, bgUUUrl;
private boolean canPlay = true;
public void runMusic() {
final GetterForBGMusic player = new GetterForBGMusic();
player.play();
}
public void play() {
URL inTTT = getClass().getResource("../sounds/bgMusic.mp3");
try (AudioInputStream in = getAudioInputStream(inTTT)) {
AudioFormat outFormat = getOutFormat(in.getFormat());
Info info = new Info(SourceDataLine.class, outFormat);
try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
System.out.println(canPlay);
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
while (true) {
System.out.println(this.getCanPlay());
}
}
public void setCanPlay(boolean play) {
this.canPlay = play;
}
public boolean getCanPlay() {
return canPlay;
}
private void booleanValue() {
while (true)
System.out.println(canPlay);
}
}
Im using this code, if i call booleanValue method in constructor, everything is fine. but if call this method inside stream there is no change after value change.
Or can someone tell me how to stop this: http://odoepner.wordpress.com/2013/07/19/play-mp3-or-ogg-using-javax-sound-sampled-mp3spi-vorbisspi/
Your program is single-threaded, which means that it executes the sequence of "commands" you programmed from top to bottom.
For example, in this example
setCanPlay(true);
play(); //your for loop
setCanPlay(false);
the setCanPlay(false) instruction will only execute once the for loop has finished executing.
What you need is to have the for loop running in the background, and to be able to modify canPlay while the for loop is running. That's called multi-threading and you should lookup the classes Runnable, Task and Service in the java api doc to learn how to implement it.
You would end up with something like this:
setCanPlay(true);
play(); //your for loop, launched in another thread.
setCanPlay(false); // Executed while the for loop is running
That would start and end the playing instantly.
Multithreading is the only way to stop an executing program (from the outside).

Run a task based on a trigger java

I want to run a task if there is a trigger (i.e. Some event like new file added to directory) in Java. Does Java have inbuilt support for this?
If not, what third party library I can use to facilitate this?
In Java 7 there is the Watch Service that allows a task to happen when a change or event is detected on a file or directory.
Tutorial: http://docs.oracle.com/javase/tutorial/essential/io/notification.html#overview
API documentation: http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html
Here is a quick example I've cooked up:
package watcher;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Watcher {
private final FileCreatedAction action;
private final String pathToWatchString;
public Watcher(FileCreatedAction action, String pathToWatchString) {
this.action = action;
this.pathToWatchString = pathToWatchString;
}
public void start() throws IOException {
FileSystem defaultFileSystem = FileSystems.getDefault();
WatchService watchService = defaultFileSystem.newWatchService();
Path pathToWatch = defaultFileSystem.getPath(pathToWatchString);
pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while(true) {
try {
WatchKey key = watchService.take();
if (key != null) {
for (WatchEvent<?> event: key.pollEvents()) {
if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE))
{
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path fullFilename = pathToWatch.resolve(filename);
action.performAction(fullFilename);
}
}
}
} catch (InterruptedException error) {
return;
}
}
}
public static void main(String[] args) throws IOException {
FileCreatedAction action = new FileCreatedAction() {
#Override
public void performAction(Path fullPath) {
System.out.printf("Found file %s", fullPath);
}
};
Watcher watcher = new Watcher(action, "/foo");
watcher.start();
}
}
interface FileCreatedAction {
void performAction(Path fullPath);
}
You could easily implement your own file system tracker.
There's a nice, working example in here:
How to watch the file system for changes in Java 7 (JDK 7)
Generally, what you need is a design pattern called 'Observer Pattern'. You can implement your own, without needing any inbuilt support or external frameworks.
For inbuilt support, check Java's 'util' package for 'Observer' and EventListener (since Java 7) interfaces.
Also, check the following links:
1) Generic, annotation-driven event notification frameworks
2) Alternative to Java's Observable class?

Categories

Resources