How to play sound from a IP in java with Android - java

I want to run a radio station from a hill top with the studio in the valley using a radio Ethernet link of 1.1 mbs data rate below is an example code (below) that I found.
But I want the code to:
Load a text file containing the IPv4 IP address to receive sound
Read a true or false from the file re transmit from the android for another to receive to save data on such a slow connection.
Can someone help please?
import java.io.IOException;
import java.util.Vector;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.DataSink;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.NoProcessorException;
import javax.media.NotRealizedError;
import javax.media.Player;
import javax.media.Processor;
import javax.media.control.FormatControl;
import javax.media.control.TrackControl;
import javax.media.format.AudioFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;
public class SimpleVoiceTransmiter {
/**
* #param args
*/
public static void main(String[] args) {
// First find a capture device that will capture linear audio
// data at 8bit 8Khz
AudioFormat format= new AudioFormat(AudioFormat.LINEAR, 8000, 8, 1);
Vector devices= CaptureDeviceManager.getDeviceList( format);
CaptureDeviceInfo di= null;
if (devices.size() > 0) {
di = (CaptureDeviceInfo) devices.elementAt( 0);
}
else {
// exit if we could not find the relevant capturedevice.
System.exit(-1);
}
// Create a processor for this capturedevice & exit if we
// cannot create it
Processor processor = null;
try {
processor = Manager.createProcessor(di.getLocator());
} catch (IOException e) {
System.exit(-1);
} catch (NoProcessorException e) {
System.exit(-1);
}
// configure the processor
processor.configure();
while (processor.getState() != Processor.Configured){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
processor.setContentDescriptor(
new ContentDescriptor( ContentDescriptor.RAW));
TrackControl track[] = processor.getTrackControls();
boolean encodingOk = false;
// Go through the tracks and try to program one of them to
// output gsm data.
for (int i = 0; i < track.length; i++) {
if (!encodingOk && track[i] instanceof FormatControl) {
if (((FormatControl)track[i]).
setFormat( new AudioFormat(AudioFormat.GSM_RTP, 8000, 8, 1)) == null) {
track[i].setEnabled(false);
}
else {
encodingOk = true;
}
} else {
// we could not set this track to gsm, so disable it
track[i].setEnabled(false);
}
}
// At this point, we have determined where we can send out
// gsm data or not.
// realize the processor
if (encodingOk) {
processor.realize();
while (processor.getState() != Processor.Realized){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// get the output datasource of the processor and exit
// if we fail
DataSource ds = null;
try {
ds = processor.getDataOutput();
} catch (NotRealizedError e) {
System.exit(-1);
}
// hand this datasource to manager for creating an RTP
// datasink our RTP datasink will multicast the audio
try {
String url= "rtp://224.0.0.1:22224/audio/16";
MediaLocator m = new MediaLocator(url);
DataSink d = Manager.createDataSink(ds, m);
d.open();
d.start();
processor.start();
} catch (Exception e) {
System.exit(-1);
}
}
}
}
Receiver:
import java.io.IOException;
import java.net.MalformedURLException;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
public class SimpleVoiceReciver{
/**
* #param args
*/
public static void main(String[] args) {
String url= "rtp://192.168.1.111:22224/audio/16";
MediaLocator mrl= new MediaLocator(url);
if (mrl == null) {
System.err.println("Can't build MRL for RTP");
System.exit(-1);
}
// Create a player for this rtp session
Player player = null;
try {
player = Manager.createPlayer(mrl);
} catch (NoPlayerException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (MalformedURLException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (IOException e) {
System.err.println("Error:" + e);
System.exit(-1);
}
if (player != null) {
System.out.println("Player created.");
player.realize();
// wait for realizing
while (player.getState() != Player.Realized){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
player.start();
} else {
System.err.println("Player doesn't created.");
System.exit(-1);
}
}
}

It sounds perfectly possible to do this multicasting over a local network. AFAIK this will not work across the internet. Also see this : Device support for multicasting is apparently very patchy. So do your research, and make sure the Android devices you work with actually support this on a software and hardware level - many of them do not. Caveat Emptor.

Related

How to release process resource in java

How to release process resource??
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.StringTokenizer;
public class RuntimeSample{
public RuntimeSample() {
}
private void execCmd1() throws IOException {
InputStream in = null;
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
in = process.getInputStream();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
}
private void execCmd2() throws IOException {
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
why it is throwing process.getError stream is not closed,I tried to close process resource by using following
if (process != null) {
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
even it is showing process.getError stream is not closed.may i know the reason y it is showing that stream is not closed and how to close the process resource.Thanks in advance
I know this answer is somewhat late, but maybe someone else runs into the same issue.
In my project the Server runs some utility (I call it winps.exe here) regularly and it was easy to see (using RAMMAP resp. Handles) that the Java process kept a handle to each of the (terminated) child processes. Restarting the Server removed all entries from the process table.
After some experimenting, I found that explicitly calling the Garbage Collector resolved the issue.
Below you find my Java test program which I used to investigate the matter.
Note that this test program has been copied from the Server source code and isn't 100% as cleanly written as possible.
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.text.*;
import java.lang.reflect.*;
import java.util.concurrent.TimeUnit;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class StartPS
{
static Long STARTTIME_JITTER = 5000L;
synchronized public static HashMap<String,Long> getStartTimes()
{
HashMap<String,Long> result = new HashMap<String, Long>();;
final File tmp_file = new File("/tmp/starttimes.out");
String tmpfilename = null;
try {
tmpfilename = tmp_file.getCanonicalPath();
} catch (Exception e) {}
try {
ProcessBuilder pb = new ProcessBuilder(".\\winps.exe");
pb.redirectOutput(new File(tmpfilename));
pb.redirectErrorStream(true);
Process p = pb.start();
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
try {
p.waitFor();
} catch (InterruptedException ie) {
// maybe some cleanup here
}
try {
while (p.isAlive()) { // <- most likely unnecessary ;-)
Thread.sleep(100);
p.destroy();
System.gc();
}
p = null; // should help the garbage collector (eliminates a reference to the object p points to)
System.gc(); // <- most likely the key to success !
} catch (Exception e) {
System.out.println("Warning: " + e.toString());
}
} catch (Exception e) {
throw new RuntimeException("(02310251044) Process start times : " + e.toString());
}
return result;
}
public static void main(String[] argv)
{
String sMax;
int iMax = 500;
if (argv.length > 0) {
sMax = argv[0];
try {
iMax = Integer.parseInt(sMax);
} catch (Exception e) {
System.out.println("Oops : " + e.toString());
System.exit(1);
}
}
for (int i = 0; i < iMax; ++i) {
System.out.print("\r" + i);
getStartTimes();
try {
Thread.sleep(1000);
} catch (Exception e) {
// do nothing
}
}
}
}

My SOAP Web client gives a nullpointer execption when attempting to run it

IDE: Eclipse Luna SR2
Java version: 8 update 45
Server: Apache Tomcat 8.0.21
I'm creating a Dynamic Web Application in Eclipse and Associated REST and SOAP web services for a uni assignment. My question is specifically regarding the client for the web service. The client will ask the user to pick from a series of options displayed in the console by typing the option number into the console. It will then act based upon the option selected. When I try the first option, "view all articles", it gives me a null pointer exception. Full details, including classes and console output are below.
Console output:
java.lang.NullPointerException
at uts.assignment2.soap.client.NewsClient.main(NewsClient.java:24)
NewsClient.java:
package uts.assignment2.soap.client;
import java.rmi.RemoteException;
import java.util.Scanner;
import javax.xml.rpc.ServiceException;
import au.edu.uts.www._31284.wsd_news.*;
public class NewsClient {
public static void main(String[] args) throws ServiceException,
RemoteException {
NewsSOAPServiceLocator locator = new NewsSOAPServiceLocator();
NewsSOAP service = locator.getNewsSOAPPort();
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println("Select an option:");
System.out.println("1: view all articles");
System.out.println("2: delete an article");
System.out.println("3: exit");
System.out.print("enter choice: ");
int option = scanner.nextInt();
switch (option) {
case 1:
try {
for (int i = 0; i < service.getArticles().length; i++) {
Article article = service.getArticle(i);
System.out.println(article);
System.out.println();
//System.out.println(article.getAuthor());
//System.out.println();
//System.out.println(article.getPublishedDate());
//System.out.println();
//System.out.println(article.getShortText());
}
} catch (NullPointerException e) {
e.printStackTrace();
}
break;
case 2:
System.out
.print("Enter the ID of the article you wish to delete: ");
int id = scanner.nextInt();
service.deleteArticle(id);
break;
case 3:
System.exit(0);
break;
}
}
}
}
NewsSOAP.java (the service itself - the client proxies are auto-generated form the wsdl by JAX-WS):
package uts.assignment2.soap;
import java.io.IOException;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.xml.ws.Endpoint;
import uts.assignment2.*;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.bind.JAXBException;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
#WebService(targetNamespace="http://client.soap.assignment2.uts")
public class NewsSOAP {
#Resource
private WebServiceContext context;
private NewsApplication getNewsApp() throws JAXBException, IOException {
ServletContext application = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
synchronized (application) {
NewsApplication newsApp = (NewsApplication) application.getAttribute("newsApp");
if (newsApp == null) {
newsApp = new NewsApplication();
newsApp.setFilePath(application.getRealPath("WEB-INF/news.xml"));
application.setAttribute("newsApp", newsApp);
}
return newsApp;
}
}
#WebMethod
public News getArticles() {
News news = null;
try {
news = getNewsApp().getArticles();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return news;
}
#WebMethod
public Article getArticle(int id) {
Article article = null;
try {
article = getNewsApp().getArticles().getArticle(id);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
return article;
}
#WebMethod
public void deleteArticle(int id) {
try {
getNewsApp().getArticles().removeArticle(getNewsApp().getArticles().getArticle(id));
getNewsApp().updateXML();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("The ID entered does not match an article in our records. Please enter a valid ID: ");
}
}
}
My problem is that I cannot figure out where the client is falling down. I can see which line the NullPointerException points to, but I cannot figure out where it falls down. Any help is appreciated. If any extra information is required, please ask and I will endeavour to provide it. Thank you.
See my comment in below code.
NewsSOAP.java
#WebMethod
public News getArticles() {
News news = null;
try {
news = getNewsApp().getArticles(); //Recursive call of getArticles() within it's own method. Which in turn setting news=null, causing null pointer exception at service.getArticles().length in for loop.
}
NewsClient.java:
for (int i = 0; i < service.getArticles().length; i++)

OSGI bundle and threads

I am new in OSGI and i have current aim. I have 10 threads, it's writing their names in a file. After recording thread sleep random 0..1 sec. This all must be a bundle. I create it, but i'm not sure Is this correct. Can any comments?
package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Start Thred!!");
new StartThreads().Execute();
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
1
package writer;
import writer.WriterLogs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StartThreads {
public static void Execute() {
BufferedWriter writer = null;
File textFile = new File("threadLog.txt");
// if file doesnt exists, then create it
if (!textFile.exists()) {
try {
textFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(textFile, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
WriterLogs wrt = new WriterLogs(writer);
Thread worker = new Thread(wrt);
worker.setName("Nisha-" + i);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriterLogs implements Runnable {
private BufferedWriter writer;
public WriterLogs(BufferedWriter wr) {
this.writer = wr;
}
#Override
public void run() {
try
{
try {
synchronized(this.writer) {
this.writer.write(Thread.currentThread().getName() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set random 0...1 s.
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( Thread.currentThread().getName() +interruptedException);
}
}
}
This is not correct. Like Boris the Spider states, when your bundle stops, you should free any resources and stop any processing the bundle was doing. So from the stop method you should somehow signal your threads to stop as soon as they can.
In practice you might get away with letting the code run, but this is definitely not how you should write your code in OSGi (which is what you're asking).

IOException while connecting to SMTP Service (Android)

This is my class that I have created just to check whether SMTP Service is running or not on the specific port of the host. I am getting the IOException while trying to connect (I have mentioned that in the comment). Am I on the right track of doing this. Is there some other better methods to determine if the service is perfectly running or not in the host at specific port. I am using apache commons library for this.
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import java.io.IOException;
import java.net.SocketException;
import java.security.NoSuchAlgorithmException;
public class SmtpServiceTest {
String hostaddress;
Integer port;
public SmtpServiceTest(String hostaddress, Integer port) {
this.hostaddress = hostaddress;
this.port = port;
}
public Boolean execute() {
AuthenticatingSMTPClient client = null;
try {
client = new AuthenticatingSMTPClient();
client.setDefaultTimeout(10 * 1000);
// I get IOException on this line while trying to connect
client.connect(hostaddress, port);
// I am not sure about this too
if (client.execTLS()) {
return true;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(client != null && client.isConnected()) {
try {
client.logout();
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
}

ActiveMQ: How to get all messages in a queue for Receiver (Java)

Here is the Server's code:
import java.net.UnknownHostException;
import java.io.IOException;
import org.apache.activemq.transport.stomp.StompConnection;
public class Server{
public static void main(String[] args) {
try {
StompConnection con = new StompConnection();
con.open("localhost", 61618);
con.connect("admin", "admin123");
con.begin("a1");
con.send("/queue/test1", "This is test message 1");
con.send("/queue/test1", "This is test message 2");
con.send("/queue/test1", "This is test message 3");
con.commit("a1");
con.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the Client's code:
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.apache.activemq.transport.stomp.StompConnection;
import org.apache.activemq.transport.stomp.StompFrame;
import org.apache.activemq.transport.stomp.Stomp.Headers.Subscribe;
public class Client {
public static void main(String[] args) {
try {
//login.
Scanner in = new Scanner(System.in);
System.out.print("Password: ");
String pass = in.next();
if (!"123".equals(pass)){
System.out.println("Sorry, wrong password.");
}
else
{
StompConnection con= new StompConnection();
con.open("localhost", 61618);
con.connect("admin", "admin123");
con.subscribe("/queue/test1", Subscribe.AckModeValues.CLIENT);
con.begin("a2");
StompFrame mes = con.receive();
System.out.println(mes.getBody());
con.ack(message, "a2");
con.commit("a2");
con.disconnect();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have 3 messages on Server. However, I only can get 1 message per time in Client. How to get all the messages in the queue in a run? Anyone can help me?
Not entirely sure what you've tried here but to read all three is just a simple loop like:
con.begin("a2");
while (true) {
StompFrame message = null;
try {
message = connection.receive(5000);
} catch (Exception e) {
break;
}
System.out.println(mes.getBody());
con.ack(message, "a2");
}
connection.commit("a2");

Categories