I am trying to use two instances of mediaplayer. When the first instance is played the second instance is prepared in another thread.and when first instance completes the file the second instance is started.
Problem: the second instance plays only audio, video is not visible.
Observation:If i prepare the second instance with the same surface holder as that of the first and start after first instance is completed it works fine.
Here is the code
package com.THER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.THER.MessengerServiceActivities.IncomingHandler;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.VideoView;
import android.widget.ViewSwitcher;
public class MediaPlayerActivity extends Activity implements OnCompletionListener, Callback, OnPreparedListener {
private MediaPlayer mMediaPlayer1 = null;
private SurfaceView mPreview1;
private SurfaceHolder holder1;
private ViewSwitcher switcher;
Integer counter = 0;
Integer played_files = 1;
private MediaPlayer mMediaPlayer2 = null;
private SurfaceView mPreview2;
private SurfaceHolder holder2;
boolean mIsBound;
boolean finish_flag = false;
/** Messenger for communicating with service. */
Messenger mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent;
super.onCreate(savedInstanceState);
setContentView(R.layout.videoview);
doBindService();
intent = getIntent();
counter=intent.getIntExtra("counter",counter);
mPreview1 =(SurfaceView)findViewById(R.id.surfaceView1);
holder1 = mPreview1.getHolder();
holder1.addCallback(this);
holder1.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPreview2 =(SurfaceView)findViewById(R.id.surfaceView2);
holder2 = mPreview2.getHolder();
holder2.addCallback(this);
holder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer1 = new MediaPlayer();
mMediaPlayer1.setScreenOnWhilePlaying(true);
mMediaPlayer2 = new MediaPlayer();
mMediaPlayer2.setScreenOnWhilePlaying(true);
try {
mMediaPlayer1.setDataSource("/sdcard/1.mp4");
mMediaPlayer1.setDisplay(holder1);
} catch (IllegalArgumentException 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();
}
mMediaPlayer1.setOnCompletionListener(this);
mMediaPlayer1.setOnPreparedListener(this);
//mMediaPlayer2.setOnPreparedListener(this);
mMediaPlayer2.setOnCompletionListener(this);
}
private class MediaPlayerTask extends AsyncTask<MediaPlayer, Void, String> implements OnCompletionListener {
String file;
private SurfaceHolder holder;
#Override
protected String doInBackground(MediaPlayer... mp1) {
// TODO Auto-generated method stub
//mp1[0].reset();
if(counter%2 == 0)
{
file = "/sdcard/2.mp4";
holder = holder2;
}
else
{
file = "/sdcard/1.mp4";
holder = holder1;
}
try {
mp1[0].reset();
mp1[0].setDataSource(file);
mp1[0].setDisplay(holder);
mp1[0].prepare();
mp1[0].setOnCompletionListener(this);
//mp1[0].start();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException 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();
}
return null;
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
public void onCompletion(MediaPlayer mp)
{
if(counter%2 == 0)
{
played_files++;
mMediaPlayer1.stop();
mMediaPlayer1.release();
mMediaPlayer2.start();
}
else
{
played_files++;
mMediaPlayer2.stop();
mMediaPlayer2.release();
mMediaPlayer1.start();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
if(counter%2 == 0)
{
mMediaPlayer2.prepare();
}
else
{
mMediaPlayer1.prepare();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
//if(counter == 1)
mp.start();
}
}
Please take a look at the following thread:
http://groups.google.com/group/android-developers/browse_thread/thread/7d08a124a2e48bb3?pli=1
It looks like using two SurfaceViews was not intended by the Android developers.
Related
I searched the google and even the stackoverflow for the solution, but nothing worked and this is really making me insane now. :(
I want the only item to be highlighted is the one which I click on the listview. When I click on the item, it gets highlighted in red color. But once I scroll the list, I find multiple items are getting highlighted with red, and coming back to the item I find it turned to default color, that is non-highlighted mode. Getting crazy over this, working on this from the past 3 hours still unable to find a solution. :( Would really appreciate your advice. I know this is my third post in a day but I am quite new to android, so stumbling over this a few times. My code is stated below-
package com.example.mp3;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> listAdapter ;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title;
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
//list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
Scanner("/sdcard/");///storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
///////////////////changing list item background on click///////////////////
//view.setSelected(true); ///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
String selected = listTest.get(position);
list.setItemChecked(position, true);//
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
}
else
{
index = (list.getAdapter().getCount()-1)-1;
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} 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();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.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();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} 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();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.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();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
play.setImageResource(R.drawable.play);
}
/*#Override
protected void onStop() {
super.onStop();
mp.stop();
Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
}*/
}
I tried to write the music player code in android.I want to show the current title of the song,artist and album image.
The Activity is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.PlayMusicService.LocalBinder;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GetMusic extends Activity implements OnGestureListener {
static Handler seekhandler=new Handler();
boolean isServiceConnected=false;
PlayMusicService playServ;
static TextView tv1,tv2,tv3;
Button previous,next;static ImageView img;static GestureDetector gDetector;
int pausePressed=1;static SeekBar sb;
int currentIndex=0;Cursor cursor;GenericSongClass GSC;
static MediaPlayer mediaPlayer;static int posofaudiotrack;
private ServiceConnection conn=new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isServiceConnected=false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder=(LocalBinder)service;
playServ=binder.getService();
isServiceConnected=true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_music);
gDetector= new GestureDetector(this);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
tv3=(TextView)findViewById(R.id.textView3);
getSongs();
img=(ImageView)findViewById(R.id.imageView1);
sb=(SeekBar)findViewById(R.id.seekBar1);
try{
Intent serv = new Intent(this,PlayMusicService.class);
bindService(serv, conn, Context.BIND_AUTO_CREATE);
System.out.println("in try calling service");
startService(serv);
}
catch(Exception e){
System.out.println("Exception is"+e);
}
System.out.println("after binding");
/*
try {
playSong(0);
}
catch(Exception e){
System.out.println("Exception is"+e);
}*/
//PlayMusic p=new PlayMusic();
// p.execute();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isServiceConnected) {
unbindService(conn);
isServiceConnected = false;
}
}
public static void mediaPlayerPause()
{
if(mediaPlayer!=null)
{
mediaPlayer.pause();
posofaudiotrack=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mediaPlayer!=null&&!mediaPlayer.isPlaying())
{
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
}
public class PlayMusic extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getSongs();
return null;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public static ArrayList<GenericSongClass> songs = null;
public void getSongs() {
Toast.makeText(getApplicationContext(), "in BindAllSongs()", Toast.LENGTH_SHORT).show();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.COMPOSER,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ALBUM
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = getBaseContext().getContentResolver().query(uri,
projection, selection, null, sortOrder);
/* int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String s=cursor.getString(column_index);*/
// Toast.makeText(getApplicationContext(), "path is"+s, Toast.LENGTH_SHORT).show();
// System.out.println("path is"+s);
if (null == cursor) {
Log.e("error","cursor is null");
// If the Cursor is empty, the provider found no matches
} else if (cursor.getCount() < 1) {
Log.i("info","cursor count<1");
} else {
songs = new ArrayList<GenericSongClass>(cursor.getCount());
cursor.moveToFirst();
int colIndex=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = cursor.getString(colIndex);
// Toast.makeText(getApplicationContext(), "PATH IS"+path, Toast.LENGTH_SHORT).show();
System.out.println("PATH IS"+path);
while (!cursor.isAfterLast()) {
GSC = new GenericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songComposer=cursor.getString(3);
GSC.title=cursor.getString(4);
GSC.album=cursor.getString(5);
songs.add(GSC);
cursor.moveToNext();
}
// Toast.makeText(getApplicationContext(), "songs first is"+songs.get(0).songTitle, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "songs length is"+songs.size(), Toast.LENGTH_SHORT).show();
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.e("I", "Media player has been loaded to memory !");
}
});
/*for(int i=0;i<songs.size();i++){
if(mediaPlayer.isPlaying())
mediaPlayer.reset();
String p=songs.get(i).songData;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "exception is"+ex, Toast.LENGTH_SHORT).show();
Log.i("ex is",ex.toString());
} finally {
if (cursor != null) {
cursor.close();
}}
}
protected void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
protected void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
private void playSong(int index) {
// TODO Auto-generated method stub
try{
mediaPlayer.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tv1.setText(songs.get(index).title);
tv2.setText(songs.get(index).album);
tv3.setText(songs.get(index).songArtist);
// tv3.append(songs.get(index).album);
mediaPlayer.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mediaPlayer.start();
sb.setMax(mediaPlayer.getDuration());
seekUpdation();
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
mediaPlayer.seekTo(seekBar.getProgress());
seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
playServ.getNextSong();
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
sb.setProgress(mediaPlayer.getCurrentPosition());
seekhandler.postDelayed(run, 1000);
}
public class GenericSongClass {
String songTitle = "";
String songArtist = "";
String songData = "";
String songComposer="";
String title="";
String album="";
String isChecked = "false";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_music, menu);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float velocityX,
float velocityY) {
pausePressed=1;//int x=playServ.getCurrentIndex();
// TODO Auto-generated method stub
if(start.getRawX() < finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "chanegd", Toast.LENGTH_SHORT).show();
if(playServ!=null){
/* if(x==0)
x=songs.size()-1;
else{
x=currentIndex-1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getPreviousSong();}
else
System.out.println("ms null");
}
else if(start.getRawX()>finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "changed on other", Toast.LENGTH_SHORT).show();
Log.d("onFLing","in onFling");
if(playServ!=null){
/*
if(x == songs.size()-1){
x=0;
}
else
{
x=x+1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getNextSong();
}
else
System.out.println("ms null");
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
System.out.println("PAUSEPRESSED"+pausePressed);
if(pausePressed==1){
pausePressed=0;
playServ.mediaPlayerPause();
}else if(pausePressed==0){
pausePressed=1;
//mediaPlayer.seekTo(posofaudiotrack);
playServ.mediaPlayerResume();
}
return true;
}
}
and the Service is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.GetMusic.GenericSongClass;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class PlayMusicService extends Service{
MediaPlayer mp;int currentIndex=0;
ArrayList<GenericSongClass> songs=GetMusic.songs;int pausePressed=1;
IBinder servbind=new LocalBinder();
public class LocalBinder extends Binder{
PlayMusicService getService()
{
return PlayMusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return servbind;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mp=new MediaPlayer();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
System.out.println("in onPrepared");
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
getNextSong();
}
});
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
System.out.println("in try");
playSong(0);
}
catch(Exception e){
System.out.println("in catch and exception is "+e.getMessage());
}
}
public void playSong(int index){
// TODO Auto-generated method stub
try{
System.out.println("in playsong");
mp.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
GetMusic.tv1.setText(songs.get(index).title);
GetMusic.tv2.setText(songs.get(index).album);
GetMusic.tv3.setText(songs.get(index).songArtist);
GetMusic.tv3.append(songs.get(index).album);
mp.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
GetMusic.img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mp.start();
GetMusic.sb.setMax(mp.getDuration());
seekUpdation();
GetMusic.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
mp.seekTo(seekBar.getProgress());
GetMusic.seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
GetMusic.sb.setProgress(mp.getCurrentPosition());
GetMusic.seekhandler.postDelayed(run, 1000);
}
public int getCurrentIndex(){
return currentIndex;
}
public void mediaPlayerPause()
{
if(mp!=null)
{
mp.pause();
//pos=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mp!=null&&!mp.isPlaying())
{
mp.seekTo(mp.getCurrentPosition());
mp.start();
}
}
public void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
public void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.start();
return 0;
}
#Override
public void onDestroy()
{
mp.release();
super.onDestroy();
}
}
The issue is it's playing good sometimes and sometimes it's stopping when we press back button or swiping other apps on home screen.I want to show the title track,image on UI.But with this code it's showing wrong images for some songs and for some it's even not showing the image even if the image exists.And after back screen pressed and so when we use other apps and get back to this It's showing simply TextView and normal android image.Is recreation of activity needed?Can we call Activity method from Service?How to solve the issues?Please help me.
You need background music service and communicate with Activity with message or bond activity to service, not call Activity method from service, that will cause cross process problem.
I actually opensource a Music Player with Background service, Lyric, from a business project I have wrote, you check this out:https://github.com/Wangchao0721/MusicPlayer
But I haven't got time to fill Readme for it, just check MediaPlayerActivity.java in activity package, you gonna know how to use this.
I have a problem with my soundboard im quite new to programming and i need help from some pros
The Problem is that my soundboard doesnt stop when i press the home button or the return button i need it to pause the sound or stop it here is the code hope you can help
package com.example.firstly;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Mymenu extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.dinal, R.id.ele, R.id.syl,
R.id.amel, R.id.krz, R.id.mar,
R.id.sra, R.id.bab, R.id.har,
R.id.kur, };
final int[] soundIds = { R.raw.dinal_ama, R.raw.daj_ama, R.raw.syl_ama,
R.raw.ame_ama, R.raw.krzy_ama, R.raw.marihuanen_ama,
R.raw.srac_ama, R.raw.zajeb_ama, R.raw.hardcore_ama,
R.raw.oookurwa_ama, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException 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 {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener); }
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Stop or pause the player in your activity's on pause, use the code below
package com.example.firstly;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Mymenu extends Activity {
int selectedSoundId;
MediaPlayer player;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.dinal, R.id.ele, R.id.syl, R.id.amel,
R.id.krz, R.id.mar, R.id.sra, R.id.bab, R.id.har, R.id.kur, };
final int[] soundIds = { R.raw.dinal_ama, R.raw.daj_ama, R.raw.syl_ama,
R.raw.ame_ama, R.raw.krzy_ama, R.raw.marihuanen_ama,
R.raw.srac_ama, R.raw.zajeb_ama, R.raw.hardcore_ama,
R.raw.oookurwa_ama, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException 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 {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
player.stop(); // to stop the player
player.release(); // if you want to pause the song use player.pause();
}
}
I am trying to play an url but its not playing and the code i used is below..the logcat is showing Mediaplayer error(1,-1002), start state is 0 and error(-38, 0) why...? where i am going wrong......can u help me out how to play........
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class BacaFatihahActivity extends Activity {
final String songs_urIs= "http://stream.radiosai.net:8002/";
// private TextView txt_song_title;
private MediaPlayer mediaplayer;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton btn_play = (ImageButton) findViewById(R.id.button_play);
ImageButton btn_pause = (ImageButton) findViewById(R.id.button_pause);
ImageButton btn_next = (ImageButton) findViewById(R.id.button_next);
ImageButton btn_previous = (ImageButton) findViewById(R.id.button_Previous);
//txt_song_title = (TextView) findViewById(R.id.txt_song_title);
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
mediaplayer.setDataSource(songs_urIs);
} catch (IllegalArgumentException 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();
}
});
}
}
right code but wrong api level~
it's not every api level supports this way to play a media,http live streaming ,may be you need api level 10 or higher
Hi I used the following code to call an activity when audio play get finished. But I want to play the audio in current activity, when play get finished it has to jump for the next activity. But here it jumps to the next activity and play the audio. Any suggestions.
package com.fsp.mus;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class MyRecording extends Activity{
String mFileName;
MediaPlayer mPlayer;
Boolean stopplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myrecording);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
} 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 {
mPlayer.prepare();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mPlayer.start();
if(mPlayer.getCurrentPosition()== mPlayer.getDuration())
{
Intent stopplay=new Intent(MyRecording.this,Recorded_Message.class);
startActivity(stopplay);
}
}
}
mPlayer.setOnCompletionListener(new
OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Intent stopplay= new Intent(MyRecording.this,Recorded_Message.class);
startActivity(stopplay);
}
});
I'll try to explain what is wrong in your code.
onCreate calls only one time when an Activity creates. So, in your code you set a source for your mPlayer:
mPlayer.setDataSource(mFileName);
then prepare it:
mPlayer.prepare();
and then starts playing:
mPlayer.start();
As you just started mPlayer, of cource if statment will be false and the code in if will never be performed:
if(mPlayer.getCurrentPosition()== mPlayer.getDuration())
{
Intent stopplay=new Intent(MyRecording.this,Recorded_Message.class);
startActivity(stopplay);
}
I remind you that onCreate is called only once.
So, use event as described above.