[Q] Mediacontroller does not display - Java for Android App Development

I have enabled the media controller in the onprepared listener . But i cannot view the media controller when run.
But the audio song is playing.
Please tell me where i did the mistakes.Here is my code:
public class Tabact1 extends Activity implements OnPreparedListener,MediaPlayerControl{
MediaPlayer mediaPlayer;
MediaController controller;
private Handler handler=new Handler();
private String audioFile;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabact1);
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
controller=new MediaController(this);
try {
mediaPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://com.example.tablayout/" + R.raw.sample));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
@override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
controller.setMediaPlayer(this);
handler.post(new Runnable() {
@override
public void run() {
// TODO Auto-generated method stub
controller.setEnabled(true);
controller.show();
}
});
}
@override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
controller.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
@override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
controller.show();
return false;
}
@override
public boolean canPause() {
// TODO Auto-generated method stub
return true;
}
@override
public boolean canSeekBackward() {
// TODO Auto-generated method stub
return true;
}
@override
public boolean canSeekForward() {
// TODO Auto-generated method stub
return true;
}
@override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
@override
public int getCurrentPosition() {
// TODO Auto-generated method stub
return mediaPlayer.getCurrentPosition();
}
@override
public int getDuration() {
// TODO Auto-generated method stub
return mediaPlayer.getDuration();
}
@override
public boolean isPlaying() {
// TODO Auto-generated method stub
return mediaPlayer.isPlaying();
}
@override
public void pause() {
// TODO Auto-generated method stub
mediaPlayer.pause();
}
@override
public void seekTo(int arg0) {
// TODO Auto-generated method stub
mediaPlayer.seekTo(arg0);
}
@override
public void start() {
// TODO Auto-generated method stub
mediaPlayer.start();
}
}

Related

[Q] How Do I Stop a Media Player

I coded an application that plays a radio stream. The App is very simple just start and stop.
When I press start, the stream plays just fine. But when I call stop, nothing happens.
Here is the code (items in red have been changed to protect the identity of this app ).:
Code:
package [COLOR="red"]com.xxxxxx.stream[/COLOR];
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class [COLOR="red"]NameOfAppActivity[/COLOR] extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("[COLOR="red"]http://xxxxx.xxxxxx.com/stream[/COLOR]");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
setContentView(R.layout.main);
}
private void Stop(){
mp.release();
}
}
I have also tried
Code:
private void Stop(){
mp.stop();
}
}
and
Code:
private void Stop(){
mp.pause();
}
}
Nothing seems to work. I have to force close the app in order to stop it.
What am I doing wrong? Please help.
mp.release() should do it. Have you tried the debugger to make sure that Stop() is being hit? I don't see why it wouldn't, but that's always the first thing I check when things don't behave like I think they should.
Thanks Gene Poole. I will try debugging it when I am home. It's extremely frustrating. I changed the code to:
Code:
private void Stop(){
if (mp != null){
mp.stop();
mp.release();
}
}
Thanks for your input.
Thanks. I figured it out. However. If I hit release, it doesn't play the stream again. The app just FCs. For now I have it set to stop
How did you figure it out?
I see the same behavior.
I/HTTPStream( 194): 1358 Bytes read, progress 64711/65536
Still keeps going, even when I call mediaplayer.stop();
One way that does stop it is to call reset(), but that also hangs for a bit.
Here is the revised code. There is no release in there but I'll figure it out soon.
Code:
package com.xxxxxx.stream;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NameOfAppActivity extends Activity {
private Button start;
private Button stop;
MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Start();}});
stop.setOnClickListener(new Button.OnClickListener() {public void onClick (View v){Stop();}});
}
private void Start() {
try {
mp.setDataSource("http://xxxxx.xxxxxx.com/stream");
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
private void Stop(){
if (mp != null){
mp.stop();
}
}
The code works fine for the most part. However if I am running the stream and exit the app and comeback to the app, I can not stop it. How do I restore the application's previous state.

Help With Grid Views

Hi everyone I'am using to grid view when i click an item on grid view 1 it should be added to grid view 2
It is added but the grid view one is scrambled up
Here is the code
Code:
mImageViews = new ArrayList<WeakReference<ImageView>>();
private ArrayList<String> mImageRepositoryTh = new ArrayList<String>(); //Thumbnails size image paths
private ArrayList<String> mImageRepositoryFu = new ArrayList<String>();//Full size image paths
private ArrayList<WeakReference<ImageView>> mWeakReferences = new ArrayList<WeakReference<ImageView>>();
private GridView mListView;
private GridView mSelected;
mListView = (GridView)findViewById(R.id.images_view);
mListView.setAdapter(new ImageAdapter(this));
mSelected = (GridView)findViewById(R.id.images_view_sel);
mChecked = new boolean[mListView.getCount()];
Log.e("ERR", "Array Length "+String.valueOf(mChecked.length));
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
mChecked[arg2] = !mChecked[arg2];
mWeakReferences.add(new WeakReference<ImageView>((ImageView)arg1));
mSelected.setAdapter(new SelectedImageAdapter());
}
});
Code:
Adapters
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(@SuppressWarnings("unused")Context c)
{
}
public int getCount() {
return mImageRepositoryTh.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
private boolean loadingFailed = false;
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if(convertView != null)
{
try
{
if (mImageViews.get(position).get() != null)
{
return mImageViews.get(position).get();
}
}
catch(IndexOutOfBoundsException E)
{
Log.e("Not Yet Inflate", "Array Index Out \n", E);
}
}
imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
mImageLoader.displayImage("file://"+mImageRepositoryTh.get(position), imageView, mOptions,new
ImageLoadingListener() {
public void onLoadingStarted(String imageUri, View view) {
// TODO Auto-generated method stub
}
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
// TODO Auto-generated method stub
loadingFailed = true;
}
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// TODO Auto-generated method stub
}
public void onLoadingCancelled(String imageUri, View view) {
// TODO Auto-generated method stub
}
});
if (loadingFailed) {
mImageLoader.displayImage("file://"+mImageRepositoryFu.get(position),imageView ,mOptions);
loadingFailed = false;
}
mImageViews.add(new WeakReference<ImageView>(imageView));
return imageView;
}
}
private class SelectedImageAdapter extends BaseAdapter
{
public SelectedImageAdapter()
{
}
[user=439709]@override[/user]
public int getCount() {
return mWeakReferences.size();
}
[user=439709]@override[/user]
public Object getItem(int i) {
return null;
}
[user=439709]@override[/user]
public long getItemId(int i) {
return i;
}
[user=439709]@override[/user]
public View getView(int position, View convertView, ViewGroup parent)
{
WeakReference<ImageView> iViewRef = mWeakReferences.get(position);
return iViewRef.get();
}
}
My apologies for ads
Download the apk from attachments

cant find out where to put OnCompletion and how

Im working with a java script.
I have two MediaPlayers in the same script
MediaPlayer MP;
MediaPlayer MP1;
Im still kind of new to the Java programming.
I want my MP to continue playing but set the volume to 5 (out of 100)
still the MP1 plays at 100.
When MP1 is complete - MP has to set volume to 100.
Here my problem. I have a huge problem with where i have to put the MP.onCompletion?
Hope you guys can help
Code:
//Reklame2
Button btn10 = (Button) findViewById(R.id.btn10);
btn10.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
if (MP1.isPlaying()){
MP1.stop();
}
else {
MP1.reset();
try {
MP1.setDataSource("file:///mnt/sdcard/data/musikapp/Reklame2.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MP1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MP.setVolume(5, 5);
MP1.start();
}
}});
zimzux said:
Im working with a java script.
I have two MediaPlayers in the same script
MediaPlayer MP;
MediaPlayer MP1;
Im still kind of new to the Java programming.
I want my MP to continue playing but set the volume to 5 (out of 100)
still the MP1 plays at 100.
When MP1 is complete - MP has to set volume to 100.
Here my problem. I have a huge problem with where i have to put the MP.onCompletion?
Hope you guys can help
Code:
//Reklame2
Button btn10 = (Button) findViewById(R.id.btn10);
btn10.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
if (MP1.isPlaying()){
MP1.stop();
}
else {
MP1.reset();
try {
MP1.setDataSource("file:///mnt/sdcard/data/musikapp/Reklame2.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MP1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MP.setVolume(5, 5);
MP1.start();
}
}});
Click to expand...
Click to collapse
When you create the player add this:
Code:
MP1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//do your stuff here
}
});

Playing videos using mediastore with custom player

Not that anyone will actually reply but I'm about to go insane to be honest, ALL i want to do is play a video from a list view using media store and a custom video player (Not stock player!) but so far all my attempts have failed.
So i need some professional help!
My MediaStore code:
Code:
public class VideoManager {
public VideoManager() {
}
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getPlayList(Context c) {
/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA}, null, null,
"UPPER(" + MediaStore.Video.Media.TITLE + ") ASC");
String videoTitle = "";
String videoPath = "";
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
videoTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
videoPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
HashMap<String, String> video = new HashMap<String, String>();
video.put("videoTitle", videoTitle);
video.put("videoPath", videoPath);
videoList.add(video);
} while (mCursor.moveToNext());
}
mCursor.close(); //cursor has been consumed so close it
return videoList;
}
public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}
}
The list code along with an OnItemClick method and Intent:
Code:
public class VideoActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
ListView videolist;
Cursor mCursor;
int videoTitle;
int count;
int videoPath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos);
ArrayList<HashMap<String, String>> videoListData = new ArrayList<HashMap<String, String>>();
VideoManager plm = new VideoManager();
// get all songs from sdcard
this.videoList = plm.getPlayList(this);
// looping through playlist
for (int i = 0; i < videoList.size(); i++) {
// creating new HashMap
HashMap<String, String> video = videoList.get(i);
// adding HashList to ArrayList
videoListData.add(video);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, videoListData,
R.layout.video_item, new String[] { "videoTitle" }, new int[] {
R.id.videoTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int videoIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
VideoPlayerActivity.class);
Log.d("TAG","onItemClick");
// Sending songIndex to PlayerActivity
in.putExtra("videoPath", videoIndex);
startActivity(in);
// Closing PlayListView
finish();
}
});
}
}
And lastly, the players code:
Code:
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
private VideoManager videoManager;
private int currentvideoIndex = 0;
private ArrayList<HashMap<String, String>> videoList = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList(this);
}
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
currentvideoIndex = data.getExtras().getInt("videoPath");
// play selected song
playVideo(currentvideoIndex);
}
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
player.prepareAsync();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
// End SurfaceHolder.Callback
// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
return player.getCurrentPosition();
}
@Override
public int getDuration() {
return player.getDuration();
}
@Override
public boolean isPlaying() {
return player.isPlaying();
}
@Override
public void pause() {
player.pause();
}
@Override
public void seekTo(int i) {
player.seekTo(i);
}
@Override
public void start() {
player.start();
}
@Override
public boolean isFullScreen() {
return false;
}
@Override
public void toggleFullScreen() {
}
}
Right now PLEASE HELP ME!! :crying:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
EmptinessFiller said:
Why do you look up the videoPath in onActivityResult? Why do you need that Method? You'd add playVideo(getIntent().getBundle().getIntExtra("videopath")); to the end of your onCreate.
Regards
Click to expand...
Click to collapse
Hi, thanks for the reply but unfortunately it didn't work.
I assume the code i entered is correct..
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
playVideo(getIntent().getExtras().getInt("videoPath"));
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
videoManager = new VideoManager();
controller = new VideoControllerView(this);
videoList = videoManager.getPlayList();
}
public void playVideo(int videoIndex){
try {
player.setDataSource(videoList.get(videoIndex).get("videoPath"));
player.setOnPreparedListener(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Android 5.0 Lollipop Hotword detection API

I have a problem with the new Android API21, specifically the VoiceInteractorService.
I would like to use the new Hotword detection in API21. If i press a button, a hotword detection for the word 'computer' should start. The new API should provide this functionality.
When I have an Activity (MainActivity) and I want to call the createAlwaysOnHotwordDetector(String keyphrase, Locale locale, AlwaysOnHotwordDetector.Callback callback) method from the VoiceInteractorService, I get an error: java.lang.IllegalStateException: Not available until onReady() is called. I tried to solve this temporarily by using a while with try catch loop to see when onReady() is called and I can excecute the createAlwaysOnHotwordDetector() method. I found out that onReady() is never called, even after letting the system loop for 15 minutes.
It seems that the VoiceInteractionService isn't able to create an HotwordDetector.
Does anybody have an idea how to solve this problem?
Thanks in advance.
This is my Activity for calling the VoiceInteractorService.
Code:
public class MainActivity extends Activity {
Button btn;
VoiceInteractionService service;
AlwaysOnHotwordDetector.Callback callback;
Locale locale = new Locale("nl-NL");
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
ctx = getApplicationContext();
service = new VoiceInteractionService();
btn.setOnClickListener(new OnClickListener() {
// Create Hotword detector on button click
@Override
public void onClick(View v) {
service.createAlwaysOnHotwordDetector("computer", locale, callback);
}
});
callback = new Callback() {
@Override
public void onRecognitionResumed() {
// TODO Auto-generated method stub
}
@Override
public void onRecognitionPaused() {
// TODO Auto-generated method stub
}
@Override
public void onError() {
// TODO Auto-generated method stub
Log.d("error", "error");
}
@Override
public void onDetected(EventPayload eventPayload) {
// TODO Auto-generated method stub
// Display Toast message when Hotword is detected
Toast.makeText(ctx, "Hotword detected", Toast.LENGTH_LONG).show();
}
@Override
public void onAvailabilityChanged(int status) {
// TODO Auto-generated method stub
}
};
}
}
I think you need to extend your own voice interaction service before trying to create a hot word detector
I have extended this voice interaction service and called createAlwaysOnHotwordDetector in onReady function as per android developer portal guidelines. However the onReady function never got called. If you have tried this, can you please tell us how this can be made.

Categories

Resources