How to import sun.audio? - java

I am attempting to play audio for a program and I need the AudioStream class and the AudioPlayer class, but when I attempt to import them Eclipse gives me an error.
Method where used:
public static void playMusic(String filepath) {
InputStream music;
try {
music = new FileInputStream(new File(filepath));
AudioStream audio = new AudioStream(music);
AudioPlayer.player.start(audio);
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
Imports:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

Related

Variable Not Changing in If Statement with Sarxos Motion Detection

I'm trying to have my program print a few "funny" images whenever it detects motion. Everything works by itself but when I put the if(detection == true) statement into the program, the variable doesn't update. How could I get it to update inside of the motionDetected function?
I've tried using boolean and int for the variable but I think it could be with the way I've structured it.
package printstuff;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.function.Function;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
/**
* Detect motion.
*
* #author Bartosz Firyn (SarXos)
*/
public class DetectMotion implements WebcamMotionListener {
public static boolean detection = false;
public DetectMotion() {
//creates a webcam motion detector
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms
detector.addMotionListener(this);
detector.start();
}
#Override
public void motionDetected(WebcamMotionEvent wme) {
//detects motion and should change the detection variable
System.out.println("Detected motion");
detection = true;
}
public static void main(String[] args) throws IOException, Exception {
new DetectMotion();
System.in.read(); // keep program open
final String[] catImages = new String[4];
//all the images
catImages[0] = "https://i.ytimg.com/vi/3v79CLLhoyE/maxresdefault.jpg";
catImages[1] = "https://i.imgur.com/RFS6RUv.jpg";
catImages[2] = "https://kiwifarms.net/attachments/dozgry5w4ae3cut-jpg.618924/";
catImages[3] = "https://www.foodiecrush.com/wp-content/uploads/2017/10/Instant-Pot-Macaroni-and-Cheese-foodiecrush.com-019.jpg";
//statement does not work..
if(detection == true)
{
for(int i=0; i<4; i++)
{
//saves the picture inside of the array to image.jpg
String imageUrl = catImages[i];
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
//sends print job to printer
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("image.jpg");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
java.util.concurrent.TimeUnit.SECONDS.sleep(15);
}
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
//converts url into image
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}

Cannot Resolve Method 'newDataOutputStream'

I am getting an cannot resolve method error when i do this:
DataOutputStream os = newDataOutputStream(client.getOutputStream());
My imports:
import android.os.Bundle;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Code for class
#SuppressWarnings("deprecation")
class sentMessage implements Runnable {
public void run() {
try {
Socket client = serverSocket.accept();
DataOutputStream os = newDataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg + "\n Server : " + str;
handler.post(new Runnable() {
public void run() {
chat.setText(msg);
}
});
os.writeBytes(str);
os.flush();
os.close();
client.close();
} catch (IOException e) {
}
}
}
You're missing a space.
DataOutputStream os = new DataOutputStream(client.getOutputStream());
^

Sending Multiple Files Via Socket using ObjectOutputStream

I'm creating an application which I have to send multiple images one after another and I use Object(Output/Input)Stream inside of a while loop. But It only send one file I guess its the first image. Can I send multiple files with Object(Output/Input)Stream? If so, What's the issue with my code?
Server : (Sends Screenshots from PC )
package application;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ScreenCapture {
Socket socket;
ObjectOutputStream os;
Robot robot;
PrintStream ps;
public ScreenCapture() throws IOException, AWTException {
// TODO Auto-generated constructor stub
socket = SocketWrapper.getSocket();
os = new ObjectOutputStream(socket.getOutputStream());
robot = new Robot();
ps = new PrintStream(socket.getOutputStream());
new Record().start();
}
private class Record extends Thread{
#Override
public void run() {
while(true){
getScreenShot();
FileInputStream fis;
try {
File f = new File("/Users/Tomahawk/Documents/send.jpg");
fis = new FileInputStream(f);
byte[] byteArray = new byte[fis.available()];
fis.read(byteArray);
os.writeObject(byteArray);
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sent File");
}
}
}
public void getScreenShot(){
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img = robot.createScreenCapture(rect);
try {
ImageIO.write(img, "jpg", new File("/Users/Tomahawk/Documents/send.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client : (Receives Screenshots and save It on the phone)
package com.pcontrol.tomahawk.pcontrol;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ScreenCapture extends Activity {
Socket socket;
ObjectInputStream is;
OutputStream os;
Scanner scanner;
ImageView screenCap;
int filesize = 0;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_capture);
socket = SocketWrapper.getSocket();
screenCap = (ImageView) findViewById(R.id.screenCap);
new ReceiveFiles().execute();
}
private class ReceiveFiles extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
while(true) {
try {
is = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
os = new FileOutputStream("/sdcard/"+i+".jpg");
byte[] sentArray = (byte[]) is.readObject();
os.write(sentArray);
os.flush();
publishProgress();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onProgressUpdate(Void... values) {
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/"+i+".jpg");
screenCap.setImageBitmap(bmp);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_screen_capture, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
That endless loop is not so endless -- in fact, it will not even loop once.
You have a "return null" at the end of your "while(true)" block. After the first iteration, your method will return.

Why does this WAV file not play? It gives me a NullPointerException

package net.NitroCruze.mrpg.baseengine.music;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
public class CPSound implements Runnable{
AudioInputStream as1;
AudioFormat af;
Clip clip1;
DataLine.Info info;
Line line1;
public CPSound() {
Thread soundThread;
soundThread = new Thread(this, "Sound");
soundThread.start();
}
public void play() {
try{
as1 = AudioSystem.getAudioInputStream(new FileInputStream(new File("/res/music.wav")));
af = as1.getFormat();
clip1 = AudioSystem.getClip();
info = new DataLine.Info(Clip.class, af);
line1 = AudioSystem.getLine(info);
}
catch(Exception e)
{
}
if ( ! line1.isOpen() )
{
try
{
clip1.open(as1);
}
catch (Exception e)
{
}
clip1.loop(Clip.LOOP_CONTINUOUSLY);
clip1.start();
}
}
public void run()
{
play();
}
}
Why does this not work? It gives me a NullPointerException?
I found out why it wasn't working! I had put "/" before 'res/music.wav' which caused the file loading system to think I was loading from a DRIVE (eg C:/ F:/), but there was nothing before that / so it thought it was loading from a null drive, which cannot exist.

BigClip Won't Play .wav File

I am attempting to add an audio player to my application. Here's the code from the class that handles audio playing:
package me.pogostick29.audiorpg.audio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class AudioPlayer {
private AudioPlayer() { }
private static AudioPlayer instance = new AudioPlayer();
public static AudioPlayer getInstance() {
return instance;
}
private static ArrayList<BigClip> clips = new ArrayList<BigClip>();
private BigClip get(String name) {
for (BigClip clip : clips) {
if (clip.getName().equalsIgnoreCase(name)) return clip;
}
return null;
}
public void play(File file) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(file);
BigClip clip = get(file.getName());
if (clip == null) {
BigClip newClip = new BigClip(file.getName());
clips.add(newClip);
clip = newClip;
}
clip.open(audioIn);
clip.start();
}
catch (Exception e) { e.printStackTrace(); }
}
}
However, when I try to run it using:
AudioPlayer.getInstance().play(new File("audio/people/blacksmith/blacksmith01a_new.wav"));
I get the following stack trace:
javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1170)
at me.pogostick29.audiorpg.audio.AudioPlayer.play(AudioPlayer.java:38)
at me.pogostick29.audiorpg.person.people.Blacksmith.playDialogue(Blacksmith.java:12)
at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:33)
Here's the format I used when exporting the file with Audition.
Nevermind, I fixed it by using this library: http://www.javazoom.net/javalayer/javalayer.html

Categories