Music in Java (start/stop) - java

Ok, so I am making a game and the music changes when you are in different regions or if there is an interruption, like with an AI.
So I have JUST learned how to make music showup in my program, and now I am trying to make it stop, but I am unsure how to, below is a snippet of code where the music plays and then I try to overwite it with new music when an action occurs.
public static void songs(String word) {
String temp = word;
if (temp.equals("start")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
} catch (IOException e) {
System.err.println(e);
}
}
if (temp.equals("stop")) {
try {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/silence.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.stop(as);
System.out.println("stopping");
} catch (IOException e) {
System.err.println(e);
}
}
}
This is the only method I have been able to find that has the music play, but if you guys have any other suggestions please let me know.
Again, I want to have sound affects and music going, and right now all that happens is one song will play, and it will not stop under any circumstance until it hits the very end of its length. I want to be able to stop songs whenever a new one should come on, and also allow sound affects to pop up.
Thanks!
(since I am stuck on this and need an answer now I will probably repost on one or two more java sites so I can get a response ASAP, thank you though!!!!)
EDITED CODE: (still does not stop the current stream, any more suggestions appreciated)
public static void songs(String word) throws IOException {
String temp = word;
if (temp.equals("go")) {
try {
blah = new FileInputStream("C:/Users/Austin/Desktop/Storage/programimages/game/battle.wav");
} catch (Throwable e) {
e.printStackTrace();
}
AudioStream as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
}
if (temp.equals("stop")) {
//don't try and do things with a null object!
if (as != null) {
AudioPlayer.player.stop(as);
System.out.println("stopping1");
}
System.out.println("stopping2");
AudioPlayer.player.stop(as);
}
}

Currently you're creating a new AudioStream in your stop branch and calling the stop method using this. This is a different object to the one that is currently playing. Try making the AudioStream a class variable, and calling stop on that instead.
EDIT: at the top of the class containing your code...
class YourClass {
//the class member variable
private AudioStream as;
//[etc...]
In your start branch:
// 'as' has already been defined above
as = new AudioStream(blah);
AudioPlayer.player.start(as);
System.out.println("going");
In your stop branch:
try
{
//don't try and do things with a null object!
if (as != null)
{
AudioPlayer.player.stop(as);
}
System.out.println("stopping");
}
catch (IOException e)
{
System.err.println(e);
}
You may have trouble with the static identifier on your method - if you're calling this from within an instantiated class you don't need this.

I can't even access these sun.audio Objects on my Eclipse IDE--I know they are in rt.jar, but there is header info about them being proprietary and such.
Can the Java Sound library (javax.sound.sampled) handle what you want to do? Both Clip and SourceDataLine allow one to stop playback. That is a more usual way of playing sound, if you want to use native Java.
Playback into is here:
http://docs.oracle.com/javase/tutorial/sound/playing.html
But the documentation, overall, is not exactly rich with examples. There's example code at this site
http://www.jsresources.org/
and plenty of people here who could help if you run into problems with the native Java approach.

Related

Score keeping for a basic Minecraft plugin

I can't seem to find a way to store a simple scoring system for a user identifier and their score. I've tried storing it in a string and in a file, but I couldn't get it to work properly.
Here's the relevant code
public class ShiftGame extends JavaPlugin implements Listener {
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
}
#EventHandler
public void onPlayerSneak(PlayerToggleSneakEvent e){
Player player = e.getPlayer();
String name = player.getDisplayName();
if(e.isSneaking() == false){
try {
PrintWriter out;
System.out.println("Writing to data file..");
out = new PrintWriter("PlayerShiftAmounts.txt");
out.println(name);
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}
}
Minecraft has some config file class: FileConfiguration and YamlConfiguration, so I think you don't need to use java.io.*, and realy needn't to worry about file writing.
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
If you sure have to log something many times a second , I think you should try to use cache or just make a variable in Java , instead of writing into file or database every time.. I don't know why you need to log a list of which player are pressing shift?

Android Java saving to file returning IOException

i know there's probably tons of these going around (and believe me i went through a lot when trying to get this right) but i cannot seem to get this going.
I'm trying to save a list of custom objects (cars) into a file on local storage and later on load them back by clicking a button.
I've been trying to use the FileOutputStream based on many sources i've read. of some reason this worked fine when tested using simple list of strings but when it comes to my self made objects i keep getting IO exception when trying to save. if anyone can take a look at my code and tell me what am i missing (spent over 20hr trying to sort this one myself with no luck).
P.S - saving and loading methods are being called by buttons which work fine so code was neglected.
public class Main extends Activity implements OnClickListener{
public static List<Car> carList = new ArrayList<Car>();
String FILENAME = "carListFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonView_saveb;
Button buttonView_loadb;
buttonView_saveb = (Button)findViewById(R.id.saveb);
buttonView_loadb = (Button)findViewById(R.id.loadb);
buttonView_saveb.setOnClickListener(this);
buttonView_loadb.setOnClickListener(this);
#Override
public void onClick(View view){
switch (view.getId()){
case R.id.saveb:
SaveData();
break;
case R.id.loadb:
LoadData();
break;
}
}
public void LoadData(){
ArrayList<car> toReturn;
FileInputStream fis;
try {
fis = openFileInput(FILENAME);
ObjectInputStream oi = new ObjectInputStream(fis);
toReturn = (ArrayList<Car>) oi.readObject();
oi.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to load, file '"+FILENAME+"' not found");
} catch (ClassNotFoundException e) {
System.out.println("Failed to load from file '"+FILENAME+"', Class not found");
} catch (IOException e) {
System.out.println("Failed to load from file '"+FILENAME+"', I/O Exception")
}
}
// this method return io exception, no idea why
public void SaveData(){
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream of = new ObjectOutputStream(fos);
of.writeObject(diveLog);
of.flush();
of.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to save, file '"+FILENAME+"' not found");
} catch (IOException e) {
System.out.println("Failed to save to file '"+FILENAME+"', I/O Exception");
}
}
}
no matter what i do this keep getting me IO exceptions.
also note that i have a button which is adding cars to the list so i wont save an empty list (although i don't see why that should matter).
Thanks to everyone who took the time to help me.
As it seems after adding the following line:
e.printStackTrace();
to the exception catchers and following the logCat output i found that Car could not be serialized. A quick research revealed that, since Car object came from a class (Car.java), that class has to implement 'serializable' in order to get serialized and later on be deserialized.
so at the Car.java file :
public class Car implements Serializable {
I came across a good explanation for the whole process, perfect for someone as new to java as i am:
https://www.youtube.com/watch?v=6MisF1sxBTo

java - screenshot taken, but permission not granted?

I am writing an application that needs to take screenshots of the users screen.
I am using the Robot class and the createScreenCapture method to achieve this.
As the Javadoc states, the readDisplayPixels permission is needed to take a screenshot.
I then went ahead and tried to check the permission before attempting to take a screenshot.
I prepared some code to show what I did:
import java.awt.AWTPermission;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
public class ScreenshotTest {
public static void main(String[] args) {
try {
new SecurityManager().checkPermission(new AWTPermission("readDisplayPixels"));
} catch (SecurityException e) {
System.out.println("Permission not granted!");
}
try {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
System.out.println("Screenshot taken!");
} catch (Exception e) {
System.out.println("Taking screenshot failed.");
}
}
}
The console printout is:
Permission not granted!
Screenshot taken!
I am confused right now, because I did not expect that to happen. Shouldn't the createScreenCapture method throw an exception because the permission is not granted?
You are creating some new SecurityManager instead of talking to the (maybe) existing one, so try this:
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new AWTPermission("readDisplayPixels"));
}
That is, if the VM has an instance of SecurityManager, you can communicate with it to check for the restriction, and if such an instance is absent - just perform any action you want to perform. Good luck with that!
P.S. You should never shadow stacktraces with your own messages unless they carry some useful information. In your case, you just hid some impotrtant info in favour of senseless messages. Don't do that.
And just in case I didn't make it clear - the exception in second try-catch block isn't thrown because internals of Robot do communicate with system's SecurityManager, while you were talking to some new instance, which hadn't had any useful payload. Here is the actual code from Robot.java:
public synchronized BufferedImage createScreenCapture(Rectangle screenRect) {
checkScreenCaptureAllowed();
//... proceed
}
private static void checkScreenCaptureAllowed() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.AWT.READ_DISPLAY_PIXELS_PERMISSION);
}
}
You need to restructure your code, just a little:). You are close.
try {
new SecurityManager().checkPermission(new AWTPermission("readDisplayPixels"));
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
System.out.println("Screenshot taken!");
} catch (SecurityException e) {
System.out.println("Permission not granted!");
} catch (Exception e) {
System.out.println("Taking screenshot failed.");
}
When the first security exception is thrown, they will never get to the screen capture statements.
Hope that helps:)

Reusing ObjectOutputStreams in Java

I am reusing ObjectOutputStream to send updates between the two clients, this is the server code,
public void run() {
try {
toPlayer1.writeBoolean(true);
toPlayer1.flush();
while (true) {
try {
found = (boolean[][]) fromPlayer1.readObject();
player1Int = fromPlayer1.readInt();
} catch (Exception ex) {
// Handle exception here...
}
if (isWon(player1Int)) {
toPlayer1.writeInt(P1_WON);
toPlayer1.flush();
toPlayer2.writeInt(P1_WON);
toPlayer2.flush();
sendMove(toPlayer2, found, player1Int);
break;
} else {
toPlayer2.writeInt(CONTINUE);
toPlayer2.flush();
sendMove(toPlayer2, found, player1Int);
}
try {
found = (boolean[][]) fromPlayer2.readObject();
player2Int = fromPlayer2.readInt();
} catch (Exception ex) {
// Handle exception here...
}
if (isWon(player2Int)) {
toPlayer1.writeInt(P2_WIN);
toPlayer1.flush();
toPlayer2.writeInt(P2_WIN);
toPlayer2.flush();
sendMove(toPlayer1, found, player2Int);
break;
} else {
toPlayer1.writeInt(CONTINUE);
toPlayer1.flush();
sendMove(toPlayer1, found, player2Int);
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
private void sendMove(ObjectOutputStream out, boolean[][] found, int score) throws IOException {
try {
out.reset();
out.writeObject(found);
out.writeInt(score);
out.flush();
} catch (Exception ex) {
// Handle exception here...
}
out.writeInt(score);
}
the problem seems to be that some messages are not being delivered correctly, any suggestions? Am I using the flush() correctly? I have added reset(); it is still not working
update, these are the streams:
public void run() {
try {
toPlayer1 = new ObjectOutputStream(player1.getOutputStream());
fromPlayer1 = new ObjectInputStream(player1.getInputStream());
toPlayer2 = new ObjectOutputStream(player2.getOutputStream());
fromPlayer2 = new ObjectInputStream(player2.getInputStream());
regards, c
If you want an object or objects to be sent again, you need to call reset() on the ObjectOutputStream object.
The problem that reset() solves is that when you send an object in a object stream, the protocol attempts to preserve object identity. The first time you send it, the stream sends the object state. Subsequent times, it just sends a marker that says (in effect) "use this object that I sent you previously".
The reset() method says (in effect) to the ObjectOutputStream ... "forget about all objects that I sent previously".
So if you want to send the same object twice, you need to do something like this:
out.writeObject(found);
// change the state of 'found'
out.reset();
out.writeObject(found);
Note that this doesn't affect primitive values sent using their corresponding write methods. Primitive values don't have "identity" and are sent literally each time.
I should also point out that the following is very bad practice.
} catch (Exception ex) {
}
You are silently ignoring all exceptions. This is lazy and dangerous, and you are likely to come to regret it. (Don't do it even in sample code in SO Questions ... 'cos someone might copy your bad code or some Java beginner might emulate your bad habits.)

errors when using the bluetooth sample code on android developer site

I am working to add Bluetooth capabilities to my app and ultimately the device that I want to use is a headset/earpiece. I have begun assembling the code and I partial functionality with it. When I got to the code for setting up a bluetooth connection by server, I got errors when adding the code. I have tried solving the problems through the hover over the error and autocorrect but every time I fix one problem a different on arises. This leads me to believe that I am missing something that autocorrect doesn't know about. I need some help fixing the errors. Useful suggestions for setting a bluetooth codin for the first time would also be appreciated. Errors are surrounded with ||#| xxx |||. Error 1:cannot be resolved. Error 2:cannot be resolved to a variable. Error 3:undefined for the type AcceptSocket.
import java.io.IOException;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public class AcceptSocket extends Thread {
private static final String MY_UUID = null;
BluetoothServerSocket mmServerSocket;
public void AcceptThread() {
// Use a temporary object that is later asssigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = ||1|mBluetoothAdapter|||.listenUsingRfcommWithServiceRecord(||2|NAME|||,
MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
||3|manageConnectedSocket|||(socket);
mmServerSocket.close();
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
Error 1,2: There is no constant called NAME anywhere in the class.
Error 3: There is no method called manageConnectedSocket() in the class.
You can't just copy and paste something from the developer's page and expect it to work. It leads you in the correct direction and you have to fill in the missing pieces.

Categories

Resources