How to solve java.lang.IllegalStateException?
This happens when moving to another activity
this logcat :
05-24 01:48:07.312 25905-25905/andie16n.abc_ind_english E/MediaPlayer:
prepareAsync called in state 8, mPlayer(0x9a318160)
this java code :
package andie16n.abc_ind_english;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
/**
* Created by andie on 11/05/2017.
*/
public class Abc_play_all extends Activity implements MediaPlayer.OnCompletionListener {
private ImageButton tombol_play;
private ImageButton tombol_play_a;
private ImageButton tombol_play_b;
private ImageButton tombol_play_c;
private ImageButton tombol_play_d;
private ImageButton tombol_play_e;
private ImageButton tombol_play_f;
private ImageButton tombol_play_g;
private ImageButton tombol_play_h;
private ImageButton tombol_play_i;
private ImageButton tombol_play_j;
private ImageButton tombol_play_k;
private ImageButton tombol_stop;
private MediaPlayer MPlayer;
private MediaPlayer MPlayer_a;
private MediaPlayer MPlayer_b;
private MediaPlayer MPlayer_c;
private MediaPlayer MPlayer_d;
private MediaPlayer MPlayer_e;
private MediaPlayer MPlayer_f;
private MediaPlayer MPlayer_g;
private MediaPlayer MPlayer_h;
private MediaPlayer MPlayer_i;
private MediaPlayer MPlayer_j;
private MediaPlayer MPlayer_k;
private MediaPlayer MPlayer_back;
private ImageButton back_abc_home_play_all;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.abc_play_all);
tombol_play_a = (ImageButton) findViewById(R.id.Btn_a_play);
tombol_play_b = (ImageButton) findViewById(R.id.Btn_b_play);
tombol_play_c = (ImageButton) findViewById(R.id.Btn_c_play);
tombol_play_d = (ImageButton) findViewById(R.id.Btn_d_play);
tombol_play_e = (ImageButton) findViewById(R.id.Btn_e_play);
tombol_play_f = (ImageButton) findViewById(R.id.Btn_f_play);
tombol_play_g = (ImageButton) findViewById(R.id.Btn_g_play);
tombol_play_h = (ImageButton) findViewById(R.id.Btn_h_play);
tombol_play_i = (ImageButton) findViewById(R.id.Btn_i_play);
tombol_play_j = (ImageButton) findViewById(R.id.Btn_j_play);
tombol_play_k = (ImageButton) findViewById(R.id.Btn_k_play);
tombol_play = (ImageButton) findViewById(R.id.Btn_play_all_abc);
tombol_stop = (ImageButton) findViewById(R.id.Btn_stop_all_abc);
tombol_stop.setEnabled(false);
aktif();
tombol_play_a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_a();
}
});
tombol_play_b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_b();
}
});
tombol_play_c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_c();
}
});
tombol_play_d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_d();
}
});
tombol_play_e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_e();
}
});
tombol_play_f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_f();
}
});
tombol_play_g.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_g();
}
});
tombol_play_h.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_h();
}
});
tombol_play_i.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_i();
}
});
tombol_play_j.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_j();
}
});
tombol_play_k.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_k();
}
});
tombol_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play_abc();
}
});
tombol_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MPlayer.stop();
try {
MPlayer.prepare();
MPlayer.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
}
});
}
#Override
public void onResume() {
super.onResume();
stop_back();
play_back();
}
private void TombolIsEnabled() {
tombol_play.setEnabled(true);
tombol_play_a.setEnabled(true);
tombol_play_b.setEnabled(true);
tombol_play_c.setEnabled(true);
tombol_play_d.setEnabled(true);
tombol_play_e.setEnabled(true);
tombol_play_f.setEnabled(true);
tombol_play_g.setEnabled(true);
tombol_play_h.setEnabled(true);
tombol_play_i.setEnabled(true);
tombol_play_j.setEnabled(true);
tombol_play_k.setEnabled(true);
}
private void play_a() {
MPlayer_a.stop();
try {
MPlayer_a.prepare();
MPlayer_a.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_a.start();
tombol_play_a.setImageResource(R.drawable.a_menu_2);
tombol_play_a.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_b() {
MPlayer_b.stop();
try {
MPlayer_b.prepare();
MPlayer_b.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_b.start();
tombol_play_b.setImageResource(R.drawable.b_menu_2);
tombol_play_b.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_c() {
MPlayer_c.stop();
try {
MPlayer_c.prepare();
MPlayer_c.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_c.start();
tombol_play_c.setImageResource(R.drawable.c_menu_2);
tombol_play_c.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_d() {
MPlayer_d.stop();
try {
MPlayer_d.prepare();
MPlayer_d.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_d.start();
tombol_play_d.setImageResource(R.drawable.d_menu_2);
tombol_play_d.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_e() {
MPlayer_e.stop();
try {
MPlayer_e.prepare();
MPlayer_e.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_e.start();
tombol_play_e.setImageResource(R.drawable.e_menu_2);
tombol_play_e.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_f() {
MPlayer_f.stop();
try {
MPlayer_f.prepare();
MPlayer_f.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_f.start();
tombol_play_f.setImageResource(R.drawable.f_menu_2);
tombol_play_f.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_g() {
MPlayer_g.stop();
try {
MPlayer_g.prepare();
MPlayer_g.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_g.start();
tombol_play_g.setImageResource(R.drawable.g_menu_2);
tombol_play_g.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_h() {
MPlayer_h.stop();
try {
MPlayer_h.prepare();
MPlayer_h.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_h.start();
tombol_play_h.setImageResource(R.drawable.h_menu_2);
tombol_play_h.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_i() {
MPlayer_i.stop();
try {
MPlayer_i.prepare();
MPlayer_i.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_i.start();
tombol_play_i.setImageResource(R.drawable.i_menu_2);
tombol_play_i.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_j() {
MPlayer_j.stop();
try {
MPlayer_j.prepare();
MPlayer_j.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_j.start();
tombol_play_j.setImageResource(R.drawable.j_menu_2);
tombol_play_j.setEnabled(false);
tombol_stop.setEnabled(true);
}
private void play_k() {
MPlayer_k.stop();
try {
MPlayer_k.prepare();
MPlayer_k.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer_k.start();
tombol_play_k.setImageResource(R.drawable.k_menu_2);
tombol_play_k.setEnabled(false);
tombol_stop.setEnabled(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tombol_stop.isEnabled()) {
stop_all();
}
}
#Override
public void onCompletion(MediaPlayer MP) {
stop_all();
}
private void play_abc() {
MPlayer_a.stop();
MPlayer_b.stop();
MPlayer_c.stop();
MPlayer_d.stop();
MPlayer_e.stop();
MPlayer_f.stop();
MPlayer_g.stop();
MPlayer_h.stop();
MPlayer_i.stop();
MPlayer_j.stop();
MPlayer_k.stop();
MPlayer.stop();
try {
MPlayer.prepare();
MPlayer.seekTo(0);
} catch (Throwable t) {
error_(t);
}
stop_all();
MPlayer.setLooping(true);
MPlayer.start();
tombol_play.setEnabled(false);
tombol_stop.setEnabled(true);
tombol_play_a.setEnabled(false);
tombol_play_b.setEnabled(false);
tombol_play_c.setEnabled(false);
tombol_play_d.setEnabled(false);
tombol_play_e.setEnabled(false);
tombol_play_f.setEnabled(false);
tombol_play_g.setEnabled(false);
tombol_play_h.setEnabled(false);
tombol_play_i.setEnabled(false);
tombol_play_j.setEnabled(false);
tombol_play_k.setEnabled(false);
}
private void stop_all() {
tombol_stop.setEnabled(false);
tombol_play_a.setImageResource(R.drawable.a_menu);
tombol_play_b.setImageResource(R.drawable.b_menu);
tombol_play_c.setImageResource(R.drawable.c_menu);
tombol_play_d.setImageResource(R.drawable.d_menu);
tombol_play_e.setImageResource(R.drawable.e_menu);
tombol_play_f.setImageResource(R.drawable.f_menu);
tombol_play_g.setImageResource(R.drawable.g_menu);
tombol_play_h.setImageResource(R.drawable.h_menu);
tombol_play_i.setImageResource(R.drawable.i_menu);
tombol_play_j.setImageResource(R.drawable.j_menu);
tombol_play_k.setImageResource(R.drawable.k_menu);
try {
TombolIsEnabled();
} catch (Throwable t) {
error_(t);
}
}
private void aktif() {
try {
MPlayer = MediaPlayer.create(this, R.raw.abc);
MPlayer.setOnCompletionListener(this);
MPlayer_a = MediaPlayer.create(this, R.raw.a);
MPlayer_a.setOnCompletionListener(this);
MPlayer_b = MediaPlayer.create(this, R.raw.b);
MPlayer_b.setOnCompletionListener(this);
MPlayer_c = MediaPlayer.create(this, R.raw.c);
MPlayer_c.setOnCompletionListener(this);
MPlayer_d = MediaPlayer.create(this, R.raw.d);
MPlayer_d.setOnCompletionListener(this);
MPlayer_e = MediaPlayer.create(this, R.raw.e);
MPlayer_e.setOnCompletionListener(this);
MPlayer_f = MediaPlayer.create(this, R.raw.f);
MPlayer_f.setOnCompletionListener(this);
MPlayer_g = MediaPlayer.create(this, R.raw.g);
MPlayer_g.setOnCompletionListener(this);
MPlayer_h = MediaPlayer.create(this, R.raw.h);
MPlayer_h.setOnCompletionListener(this);
MPlayer_i = MediaPlayer.create(this, R.raw.i);
MPlayer_i.setOnCompletionListener(this);
MPlayer_j = MediaPlayer.create(this, R.raw.j);
MPlayer_j.setOnCompletionListener(this);
MPlayer_k = MediaPlayer.create(this, R.raw.k);
MPlayer_k.setOnCompletionListener(this);
MPlayer_back = MediaPlayer.create(this, R.raw.backsound);
} catch (Throwable t) {
error_(t);
}
TombolIsEnabled();
}
private void play_back() {
if (MPlayer_back != null && !MPlayer_back.isPlaying()) {
MPlayer_back.setLooping(true);
MPlayer_back.start();
} else {
MPlayer_back.setLooping(true);
}
}
private void stop_for_back() {
MPlayer_back.stop();
try {
MPlayer_back.prepare();
MPlayer_back.seekTo(0);
} catch (Throwable t) {
error_(t);
}
}
private void stop_back() {
if (MPlayer_back.isPlaying()) {
stop_for_back();
MPlayer_back.reset();
}
}
private void error_(Throwable t) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Failed!").setMessage(t.toString())
.setPositiveButton("OK", null).show();
}
public void btn_back_all_abc_cliked(View v) {
stop_for_back();
Intent panggil_class = new Intent(this, Abc.class);
startActivity(panggil_class);
MPlayer_a.reset();
MPlayer_b.reset();
MPlayer_c.reset();
MPlayer_d.reset();
MPlayer_e.reset();
MPlayer_f.reset();
MPlayer_g.reset();
MPlayer_h.reset();
MPlayer_i.reset();
MPlayer_j.reset();
MPlayer_k.reset();
}
#Override
public void onBackPressed() {
if (MPlayer.isPlaying() || MPlayer_back.isPlaying()) {
stop_back();
MPlayer.reset();
}
finish();
}
}
No need to prepare the player in case of the raw file
var mediaPlayer: MediaPlayer? = MediaPlayer.create(context, R.raw.sound_file_1)
mediaPlayer?.start() // no need to call prepare(); create() does that for you
I met the same mistake when I want to play a video using SurfaceView and MediaPlayer.
mMediaPlayer.prepareAsync();
mMediaPlayer.setDisplay(mSurfaceView.getHolder());
mMediaPlayer.start();
I solve the problem through the following code:
mMediaPlayer.setDisplay(mSurfaceView.getHolder());
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
But I don't know what the cause of problem is....
Related
I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});
I have created android app to stream online radio station and I want to run it in background using service.How to create service to run media player in background?
Here is source code of the application:
public class MainActivity extends AppCompatActivity
{
private ImageButton buttonPlay,buttonStop,buttonPause;
private String STREAM_URL = "http://178.149.86.162:8000/";
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
buttonStop = (ImageButton) findViewById(R.id.buttonStopPlay);
buttonPause = (ImageButton) findViewById(R.id.buttonPause);
mPlayer = new MediaPlayer();
buttonPlay.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
startService();
}
});
buttonStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.stop();
stopService();
}
});
buttonPause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.pause();
stopService();
}
});
playbackServiceIntent = new Intent(this, BackgroundService.class);
}
private void startService()
{
startService(new Intent(MainActivity.this,BackgroundService.class));
}
private void stopService()
{
stopService(new Intent(MainActivity.this,BackgroundService.class));
}
}
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL = "http://178.149.86.162:8000/";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
mediaPlayer = new MediaPlayer();
try
{
mediaPlayer.setDataSource(STREAM_URL);
} catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I want to play music in my app when application starts. I tried many codes but nothing is working for me and i'm not getting any error.Can somebody please help me regarding this issue.Thanks in advance.
public class Login extends Activity {
EditText edName, edPassword;
String userName,password;
MediaPlayer mp;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mp = MediaPlayer.create(getApplicationContext(), R.raw.startsound);
ActionBar actionBar = getActionBar();
actionBar.hide();
edName = (EditText) findViewById(R.id.editText1);
edPassword = (EditText) findViewById(R.id.editText2);
mp.start();
}
public void SignInClick(View V) {
userName = edName.getText().toString();
password = edPassword.getText().toString();
if (userName.equals("")) {
Toast.makeText(Login.this, "Username is empty", Toast.LENGTH_LONG).show();}
else if (password.equals("")) {
Toast.makeText(Login.this, "Password is empty", Toast.LENGTH_LONG).show();
}
else {
Intent intent=new Intent(Login.this,Home.class);
startActivity(intent);
}
}
Hope this helps, and should be a working example although I have not had chance to test it.
public static Music theme;
theme = createMusic("menutheme.mp3");
theme.setLooping(true);
theme.setVolume(0.85f);
theme.play();
public Music createMusic(String filename) {
try {
AssetFileDescriptor assetDescriptor = assets.openFd(filename);
return new AndroidMusic(assetDescriptor);
} catch (IOException e) {
throw new RuntimeException("Couldn't load music '" + filename + "'");
}
}
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import com.matt.framework.Music;
import java.io.IOException;
public class AndroidMusic implements Music, OnCompletionListener, OnSeekCompleteListener, OnPreparedListener, OnVideoSizeChangedListener {
MediaPlayer mediaPlayer;
boolean isPrepared = false;
public AndroidMusic(AssetFileDescriptor assetDescriptor) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
assetDescriptor.getStartOffset(),
assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
} catch (Exception e) {
throw new RuntimeException("Couldn't load music");
}
}
#Override
public void dispose() {
if (this.mediaPlayer.isPlaying()){
this.mediaPlayer.stop();
}
this.mediaPlayer.release();
}
#Override
public boolean isLooping() {
return mediaPlayer.isLooping();
}
#Override
public boolean isPlaying() {
return this.mediaPlayer.isPlaying();
}
#Override
public boolean isStopped() {
return !isPrepared;
}
#Override
public void pause() {
if (this.mediaPlayer.isPlaying())
mediaPlayer.pause();
}
#Override
public void play() {
if (this.mediaPlayer.isPlaying())
return;
try {
synchronized (this) {
if (!isPrepared)
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}
#Override
public void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
#Override
public void stop() {
if (this.mediaPlayer.isPlaying() == true){
this.mediaPlayer.stop();
synchronized (this) {
isPrepared = false;
}}
}
#Override
public void onCompletion(MediaPlayer player) {
synchronized (this) {
isPrepared = false;
}
}
#Override
public void seekBegin() {
mediaPlayer.seekTo(0);
}
#Override
public void onPrepared(MediaPlayer player) {
// TODO Auto-generated method stub
synchronized (this) {
isPrepared = true;
}
}
#Override
public void onSeekComplete(MediaPlayer player) {
// TODO Auto-generated method stub
}
#Override
public void onVideoSizeChanged(MediaPlayer player, int width, int height) {
// TODO Auto-generated method stub
}
}
I have been trying to add sound to my alphabet android application, but I don't seem to have been successful. Below is my code.
public class Sound extends Activity implements OnCompletionListener {
/** Called when the activity is first created. */
private ImageView b;
private ImageView t;
private ImageView j;
private MediaPlayer mp;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.alphabet);
b=(ImageView)findViewById(R.drawable.b);
t=(ImageView)findViewById(R.drawable.t);
j=(ImageView)findViewById(R.drawable.j);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
b();
}
});
setup();
t.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
t();
}
});
setup2();
j.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
j();
}
});
setup3();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
private void stop() {
mp.stop();
}
private void b() {
mp.stop();
loadClip();
mp.start();
b.setEnabled(true);
}
private void t() {
mp.stop();
loadClip2();
mp.start();
t.setEnabled(true);
}
private void j() {
mp.stop();
loadClip3();
mp.start();
j.setEnabled(true);
}
private void loadClip() {
try {
mp=MediaPlayer.create(this, R.raw.b);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void loadClip2() {
try {
mp=MediaPlayer.create(this, R.raw.t);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void loadClip3() {
try {
mp=MediaPlayer.create(this, R.raw.j);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void setup() {
loadClip();
b.setEnabled(true);
}
private void setup2() {
loadClip2();
t.setEnabled(true);
}
private void setup3() {
loadClip3();
j.setEnabled(true);
}
private void goBlooey(Throwable t) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder
.setTitle("Exception!")
.setMessage(t.toString())
.setPositiveButton("OK", null)
.show();
}
}
Would you please be so kind to take a look on my code and let me know where or what is missing.
All the images are in the drawable and all clips are in the raw.
Regards.
A quick skim through your code and I would say your mp doesn't exist in order to be stopping it before loading another clip on the first run.
At the top put
private MediaPlayer mp=null;
then on every line where it says mp.stop(); change it to if(mp!=null) mp.stop();