Displaying Multiple Images on a Single Google Glass Live Card - google-glass

I'm creating a live card app that recieves PNGs from a php script running on my server in response to a request from scanning QR codes. At the moment, I simply replace the image on my Live card with the PNG I recieve from the server, but I would like to recieve and display multiple images from the server with each request.
Is there an approved way to show multiple images on a live card? I was thinking there may be a possiblity of generating a menu full of images that simply closed itself when clicked, but it seems like there might be a better alternative.
This is my code at the moment:
Current Code
import com.google.android.glass.timeline.LiveCard;
import com.google.android.glass.timeline.LiveCard.PublishMode;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.util.Base64;
import android.widget.RemoteViews;
public class iotSplashScreen extends Service {
private static final String LIVE_CARD_TAG = "iotSplashScreen";
private LiveCard mLiveCard;
private RemoteViews mLiveCardView;
public class iotBinder extends Binder {
public void changeImage(String change) {
try {
byte[] bob = Base64.decode(change, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bob, 0, bob.length);
if(bitmap != null) {
mLiveCardView.setImageViewBitmap(R.id.image_view_id, bitmap);
mLiveCard.setViews(mLiveCardView);
}
else
{
System.out.println("Daaang, dat bitmap was null doe");
}
}
catch (IllegalArgumentException e)
{
System.out.println("Base64 had an issues: " + e);
System.out.println(change);
}
catch (NullPointerException e)
{
System.out.println("Null Pointer: " + e);
}
}
}
private final iotBinder mBinder = new iotBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mLiveCard == null) {
mLiveCard = new LiveCard(this, LIVE_CARD_TAG);
mLiveCardView = new RemoteViews(getPackageName(), R.layout.iot_splash_screen);
mLiveCard.setViews(mLiveCardView);
// Display the options menu when the live card is tapped.
Intent menuIntent = new Intent(this, LiveCardMenuActivity.class);
mLiveCard.setAction(PendingIntent.getActivity(this, 0, menuIntent, 0));
mLiveCard.publish(PublishMode.REVEAL);
} else {
mLiveCard.navigate();
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (mLiveCard != null && mLiveCard.isPublished()) {
mLiveCard.unpublish();
mLiveCard = null;
}
super.onDestroy();
}
}

Simply add more ImageViews, either in your layout file (iot_splash_screen) or programmatically.
With the resource IDs of your ImageViews, you can call setImageViewResource on each one.
Make sure that you are setting these images before calling setViews on your Live Card.

Related

CognitoCachingCredentialsProvider getCachedIdentityId is null after app close and re-open

I might be misunderstanding the intended behavior of this method, but this is what I am trying to use it for:
-User logs in successfully
-User closes app completely (closes in background as well)
-User opens app again and doesn't have to log in again because CognitoCachingCredentialsProvider can check locally on the device to see she's still logged in
The way I tried to accomplish this is to check, before being prompted to log in, what getCachedIdentityId() returns. If it returns not null, then that means that she's still logged in, because there was nothing that cleared her credentials from the device. Here's what my framework looks like. I'm using developer authenticated method:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.amazonaws.auth.AWSAbstractCognitoIdentityProvider;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.cognito.*;
import com.amazonaws.regions.Regions;
public class Util {
private final static String TAG = "Util";
private static final String AWS_ACCOUNT_ID = {acct id};
private static final String COGNITO_POOL_ID = {pool id};
private static final String COGNITO_ROLE_AUTH = {auth arn};
private static final String COGNITO_ROLE_UNAUTH = {unauth arn}
private static CognitoCachingCredentialsProvider sCredProvider;
private static UserIdentityProvider sIdProvider;
private static CognitoSyncManager sSyncManager;
private Util() {
}
public static CognitoCachingCredentialsProvider getCredProvider(
Context context) {
if (sCredProvider == null) {
if (sIdProvider == null) {
CognitoCachingCredentialsProvider tmpProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(), AWS_ACCOUNT_ID,
COGNITO_POOL_ID, COGNITO_ROLE_UNAUTH,
COGNITO_ROLE_AUTH, Regions.US_EAST_1);
if (tmpProvider.getCachedIdentityId() != null) {
sCredProvider = tmpProvider;
} else {
sCredProvider = null;
}
} else {
sCredProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(), sIdProvider,
COGNITO_ROLE_UNAUTH, COGNITO_ROLE_AUTH);
Map logins = new HashMap();
logins.put({Developer Provider Name}, sIdProvider.getToken());
sCredProvider.setLogins(logins);
}
}
return sCredProvider;
}
public static UserIdentityProvider getIdentityProvider(Context context,
String email, String pwd) {
if (sIdProvider == null) {
sIdProvider = new UserIdentityProvider(AWS_ACCOUNT_ID,
COGNITO_POOL_ID, context.getApplicationContext());
}
return sIdProvider;
}
public static boolean isLoggedIn(Context context) {
if (getCredProvider(context) == null) {
return false;
}
return true;
}
protected static class UserIdentityProvider extends
AWSAbstractCognitoIdentityProvider {
private Context context;
private String email;
private String password;
public UserIdentityProvider(String accountId, String identityPoolId,
Context c) {
super(accountId, identityPoolId);
context = c;
email = em;
password = pwd;
}
#Override
public String refresh() {
try {
ServerCommunicator server = new ServerCommunicator(context);
if (email != null && password != null) {
//this is a server call, which makes the call GetOpenIdTokenForDeveloperIdentityRequest after I authenticate the user and send AWS my user's token
String response = server.initUserLoginAsyncTask()
.execute(email, password).get();
prefs.setAllUserSharedPrefs(response);
JSONObject responseJSON = new JSONObject(response);
String identityId = responseJSON.getString("id");
String token = responseJSON.getString("token");
if (token != null && identityId != null) {
this.setToken(token);
this.setIdentityId(identityId);
update(identityId, token);
return token;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public String getProviderName() {
return {Developer Provider Name};
}
}
}
I simply call the isLoggedIn method from this class to see if there's an IdentityId stored locally. However, this isn't working as expected. I can see from debugging that getCachedIdentityId is always null (even directly after initializing CognitoCachingCredentialsProvider and adding the token to the logins map) and I am always prompted to log in again whenever I open the app after it has been closed. When does the IdentityId actually get stored locally and is my logic correct in general?
Additional Code
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private final String TAG = "LoginActivity";
private EditText etEmail, etPwd;
private Button bLogin, bGoToRegister;
private ServerCommunicator server;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
server = new ServerCommunicator(this);
if (Util.isLoggedIn(this)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
return;
}
this.setContentView(R.layout.activity_login);
etEmail = (EditText) findViewById(R.id.etEmail);
etPwd = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bGoToRegister = (Button) findViewById(R.id.bGoToRegister);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String email = etEmail.getText().toString();
String pwd = etPwd.getText().toString();
Util.getIdentityProvider(v.getContext()).setEmail(email);
Util.getIdentityProvider(v.getContext()).setPassword(pwd);
String token = Util.getIdentityProvider(v.getContext()).refresh();
if (token != null) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(v.getContext(), "Invalid username/password",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above is my LoginActivity. When the app starts the MainActivity, I have the following snippet at the beginning of my onCreate method:
if (!Util.isLoggedIn(this)) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
This call initializes the CognitoCachingCredentialsProvider. I assumed that this would be when the IdentityId gets cached, but my debugging has revealed that even directly after this block, getCachedIdentityId() still returns null. Am I way off base with how I'm trying to use this class?
I have one suggestion. The CognitoCachingCredentialsProvider is what saves the identityId as it's changed. It doesn't start listening, though, until it's been initialized, and the change occurs on refresh call to your identity provider.
Can you try moving the initialization of the CognitoCachingCredentialsProvider to before the refresh call (but after your identity provider initialization)?
Edit:
Update will set the identityId and token, however explicit calls made just beforehand may cause it to think no change is being made. Can you try eliminating the setter calls as well?

How to display image from url

I have image in server url then i'm passing and displaying in to Card. I have done this in android using LoaderImageView library and displaying but in Glass i'm passing the url link to card. But i got this error "The method addImage(Drawable) in the type CardBuilder is not applicable for the arguments (String)"
Code:
public static Drawable drawableFromUrl(String url) {
Bitmap x;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
} catch(MalformedURLException e) {
//Do something with the exception.
}
catch(IOException ex) {
ex.printStackTrace();
}
return null;
}
View view = new CardBuilder(getBaseContext(), CardBuilder.Layout.TITLE)
.setText("TITLE Card")
// .setIcon(R.drawable.ic_phone)
.addImage(drawableFromUrl(link))
.getView();
From the doc, addImage takes Drawable, int, or Bitmap. It doesn't take String.
You can download image using AsyncTask or thread or whatever you like and convert it to Drawable. Then, you can call addImage.
For example:
// new DownloadImageTask().execute("your url...")
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
// yourCardBuilder.addImage(link)
// or start another activity and use the image there...
}
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
I haven't tested the code but hope you get the idea.
Also see:
How to load an ImageView by URL in Android?
Android Drawable Images from URL
Edit:
private Drawable drawableFromUrl(String url) {
try {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return new BitmapDrawable(bitmap);
} catch (IOException e) {
return null;
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
protected Drawable doInBackground(String... urls) {
String url = urls[0];
return drawableFromUrl(url);
}
protected void onPostExecute(Drawable result) {
stopSlider();
if(result != null) {
mCardAdapter.setCards(createCard(getBaseContext(), result));
mCardAdapter.notifyDataSetChanged();
}
}
}
See my full example on my GitHub repo. SliderActivity might be helpful for you.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

Google glass live stream video using RTSP server of Wowza

I'm trying to build a Google glass app that supports live streaming. Am aware that Livestream app is available to do this but i don't think we can integrate it in our application or am i wrong? is there a way to integrate the livestream in our app?
I came across this https://github.com/andermaco/GlassStream open source project which do the same thing using RTSP server of Wowza. As per the instructions i have given the user name/password and updated the url. But while running there is an issue while running the application., i tried to debug it but am not successful. This is the log am getting repeatedly
java.lang.IllegalStateException at android.media.MediaCodec.dequeueOutputBuffer(Native Method)
at net.majorkernelpanic.streaming.rtp.MediaCodecInputStream.read(MediaCodecInputStream.java :75)
at net.majorkernelpanic.streaming.rtp.AACLATMPacketizer.run(AACLATMPacketizer.java:88)
at java.lang.Thread.run(Thread.java:841)
Some of the users have used and are successful, Please share me the source code or let me know if am missing something in setting up the server. Even if there are any other resource for implementing, it would be great.
Thanks in Advance.
This the code I've used to get it working on Google Glass (XE22) using Wowza media server and libstreaming.
I've two classes AppConfig and MyActivity.
AppConfig:
package com.example.GlassApp;
/**
* User: Colin Shewell
* Date: 21/08/14
* Time: 15:30
*/
public class AppConfig {
public static final String STREAM_URL = "rtsp://193.61.148.73:1935/serg/android_test";
//public static final String STREAM_URL = "rtsp://192.168.2.2:1935/serg/android_test";
public static final String PUBLISHER_USERNAME = "";
public static final String PUBLISHER_PASSWORD = "";
}
MyActivity:
package com.example.GlassApp;
/**
* User: Colin Shewell
* Date: 21/08/14
* Time: 15:30
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;
import net.majorkernelpanic.streaming.video.VideoQuality;
public class MyActivity extends Activity implements RtspClient.Callback, Session.Callback, SurfaceHolder.Callback {
// log tag
public final static String TAG = MyActivity.class.getSimpleName();
// surfaceview
private static SurfaceView mSurfaceView;
// Rtsp session
private Session mSession;
private static RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
// Initialize RTSP client
initRtspClient();
}
#Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
#Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setVideoQuality(new VideoQuality(640, 480, 20, 500000)) //only need if you want to change the resolution from default
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.setCallback(this).build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
alertError(e.getMessage());
e.printStackTrace();
}
}
private void alertError(final String msg) {
final String error = (msg == null) ? "Unknown error: " : msg;
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
builder.setMessage(error).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
alertError(exception.getMessage());
exception.printStackTrace();
break;
}
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// #Override
public void onBitrateUpdate(long bitrate) {
}
}
EDIT:
I can confirm that the following video quality settings work:
.setVideoQuality(new VideoQuality(640, 480, 20, 500000))
.setVideoQuality(new VideoQuality(960, 720, 20, 500000))
I'd also like to add that an fps value of over 20 seems to result in the app failing to start.

Jmf Mp3 files not streaming on rtp

The player mp3 gives error:
RTP Handler internal error: javax.media.ControllerErrorEvent[source=com.sun.medi
a.content.unknown.Handler#baf4ae,message=Internal module com.sun.media.BasicRend
ererModule#197f158: failed to handle a data format change!]
i m running
server as:java MediaConverterExample rtp://rajneesh-pc:49150/audio Dead_End.mp3
client as:java PlayerExample rtp://rajneesh-pc:49150/audio
this is server side code
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import javax.media.protocol.*;
import javax.media.format.AudioFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MediaConvertion
{
private MediaLocator mediaLocator = null;
private DataSink dataSink = null;
private Processor mediaProcessor = null;
private static final Format[] FORMATS = new Format[] { new AudioFormat(AudioFormat.MPEG_RTP)};
private static final ContentDescriptor CONTENT_DESCRIPTOR =new ContentDescriptor (ContentDescriptor.RAW_RTP);
public MediaConvertion(String url)throws IOException,NoProcessorException, CannotRealizeException, NoDataSinkException, NoDataSinkException
{
mediaLocator=new MediaLocator(url);
}
public void setDataSource(DataSource ds) throws IOException,NoProcessorException, CannotRealizeException, NoDataSinkException {
mediaProcessor = Manager.createRealizedProcessor(new ProcessorModel(ds, FORMATS, CONTENT_DESCRIPTOR));
dataSink = Manager.createDataSink(mediaProcessor.getDataOutput(),mediaLocator);
}
public void startTransmitting() throws IOException {
mediaProcessor.start();
dataSink.open();
dataSink.start();
}
public void stopTransmitting() throws IOException {
dataSink.stop();
dataSink.close();
mediaProcessor.stop();
mediaProcessor.close();
}
}
public class MediaConverterExample extends Frame implements ActionListener
{
Button st_stream;
static MediaConvertion mdcon;
public static void main(String args[])throws IOException,NoProcessorException, CannotRealizeException, NoDataSinkException,MalformedURLException,NoDataSourceException
{
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
File mediaFile = new File(args[1]);
DataSource source = Manager.createDataSource(new MediaLocator(mediaFile.toURL()));
mdcon=new MediaConvertion(args[0]);
mdcon.setDataSource(source);
new MediaConverterExample();
}
public MediaConverterExample()
{
st_stream=new Button("Start Streaming");
add(st_stream);
st_stream.addActionListener(this);
setVisible(true);
setSize(200,300);
}
public void actionPerformed(ActionEvent ae)
{
try
{
mdcon.startTransmitting();
}
catch(Exception e){
}
}
}
this is client side code
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.media.format.*;
public class PlayerExample extends JFrame implements ActionListener
{
Button play;
SimpleAudioPlayer sap;
PlayerExample(String playFile) throws IOException,NoPlayerException, CannotRealizeException
{
sap=new SimpleAudioPlayer(new MediaLocator(playFile));
setLayout(new BorderLayout());
//add(sap.VideoComponent(),BorderLayout.CENTER);
//add(sap.AudioComponent(),BorderLayout.WEST);
//add(sap.ControlComponent(),BorderLayout.NORTH);
add(play=new Button("play"),BorderLayout.SOUTH);
play.addActionListener(this);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
sap.play();
}
public static void main(String args[])throws IOException,NoPlayerException, CannotRealizeException
{
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
new PlayerExample(args[0]);
}
}
class SimpleAudioPlayer {
private Player videoPlayer = null;
public SimpleAudioPlayer(MediaLocator ml) throws IOException, NoPlayerException, CannotRealizeException {
videoPlayer = Manager.createRealizedPlayer(ml);
}
public void play() {
//videoPlayer.deallocate();
videoPlayer.start();
}
public void stop() {
videoPlayer.stop();
}
public Component VideoComponent(){
return videoPlayer.getVisualComponent();
}
public Component ControlComponent(){
return videoPlayer.getControlPanelComponent();
}
public Component AudioComponent(){
return videoPlayer.getGainControl().getControlComponent();
}
}
Please help I did every thing I could. Please advise me of any other details I might be missing, server runs fine, but client blocks at player creation. The audio format I am using is MPEG_RAW. Eagerly looking for an answer, thanks in advance.
SOLVED......
i figured when looked at oracle forum
change
AudioFormat.MPEG_RTP to AudioFormat.DVI_RTP
don't ask a reason why mp3 didn't work.i did everything i could.
please tell me why previous didn't work.