I can stop the Audio but if I check my Android-Studio Debug windows, i see that the MediaPlayer works in Background !!!
I play the Sound like that :
try {
myMediaPlayer1 = new MediaPlayer();
myMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
myMediaPlayer1.setDataSource("http://myweb.com/audios/1.mp3");
myMediaPlayer1.prepare();
myMediaPlayer1.start();
} catch (Exception e) {
// TODO: handle exception
}
I stop the MediaPlayer via a click on a Button or OnDestry like that :
#Override
protected void onDestroy() {
super.onDestroy();
myMediaPlayer1.stop();
}
I debug via USB Connection. After Stop the Sound I see the MediaPlay works in Background :
You need to release media player using mediaPlayer.release(). If MediaPlayer is not playing any song/audio you shouldn't stop MediaPlayer. See below code for more help.
private void releaseMediaPlayer() {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I'm building a radio streaming app. Everything works great when I have a good internet connection, even when multitasking. The problem is without or with a poor internet connection.
The moment you tap the play button the app freezes and only resumes when the audio stream starts. With slow connections this can take a few seconds, hanging the app. Without Internet, the app eventually crashes after a while.
public class SoundService extends Service {
MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
mp = new MediaPlayer();
try {
mp.setDataSource("stream_url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.v(TAG, "Error 1");
onDestroy();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.v(TAG, "Error 2");
onDestroy();
} catch (IOException e) {
e.printStackTrace();
Log.v(TAG, "Error 3");
onDestroy();
}
try {
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
Log.v(TAG, "Error 4");
onDestroy();
} catch (IOException e) {
e.printStackTrace();
Log.v(TAG, "Error 5");
onDestroy();
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
mp.start();
return Service.START_NOT_STICKY;
}
public void onDestroy() {
mp.stop();
mp.release();
stopSelf();
super.onDestroy();
}
}
This is how I start the stream (play button):
startService(new Intent(MainActivity.this, SoundService.class));
Without connection the app eventually gets the error number 5, but this occurs only when crashes, so it's too late do stop the player. Before that I don't get any "catch".
As a temporary workaround, I'm checking for internet connection before starting the stream. This way I can prevent the crash, but I still have a problem with the app hanging on slow connections.
Any ideas? Thanks!
use this code which might help you
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
I have trouble making an app that can record and listen at the same time. I have create a recorder that is able to record and play at the moment,but i would really appreciate if someone could give suggestion on how to get started with android studio so that i can make the app to record and listen at the same time.
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrec.3gp";
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void start(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
start.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(this,"Recording started",Toast.LENGTH_SHORT).show();
}
public void stop(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder=null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(this,"Audio successfully recorded",Toast.LENGTH_SHORT).show();
}
public void play(View v) throws IOException {
MediaPlayer m=new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(this,"Playing audio", Toast.LENGTH_SHORT).show();
}
}
I have developed UWP application where it play audio files in Background or when the phone is locked. The application works fine and everything seems perfect for 5-10 minutes. After that when I run the app, I cannot play audio file and I am getting the exception attached in the subject. However, If I restart the app, everything works fine again. I have followed below steps and added following code and projects to do the task.
Created Universal Project (Windows Universal)
Added following code to send Background Message
BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
Added Windows Component Runtime (Windows Universal) with following code
Added Entry Point and Background Task in Package.appxmanifest
public sealed class AudioPlayer : IBackgroundTask {
private BackgroundTaskDeferral deferral;
private SystemMediaTransportControls systemmediatransportcontrol;
public void Run(IBackgroundTaskInstance taskInstance) {
systemmediatransportcontrol = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
systemmediatransportcontrol.ButtonPressed += systemmediatransportcontrol_ButtonPressed;
systemmediatransportcontrol.PropertyChanged += systemmediatransportcontrol_PropertyChanged;
systemmediatransportcontrol.IsEnabled = true;
systemmediatransportcontrol.IsPauseEnabled = true;
systemmediatransportcontrol.IsPlayEnabled = true;
systemmediatransportcontrol.IsNextEnabled = true;
systemmediatransportcontrol.IsPreviousEnabled = true;
BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
deferral = taskInstance.GetDeferral();
taskInstance.Canceled += TaskInstance_Canceled;
taskInstance.Task.Completed += Taskcompleted;
}
void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) {
deferral.Complete();
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) {
try {
systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;
systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
}
catch (Exception) {
}
deferral.Complete();
}
void Current_CurrentStateChanged(MediaPlayer sender, object args) {
MediaPlayer player = sender;
switch (player.CurrentState) {
case MediaPlayerState.Playing:
systemmediatransportcontrol.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaPlayerState.Paused:
systemmediatransportcontrol.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
}
}
void systemmediatransportcontrol_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args) {
try {
switch (args.Button) {
case SystemMediaTransportControlsButton.Play:
playTrack();
break;
case SystemMediaTransportControlsButton.Pause:
stopBeforePlaying();
break;
case SystemMediaTransportControlsButton.Next:
stopBeforePlaying();
nextTrack();
break;
case SystemMediaTransportControlsButton.Previous:
stopBeforePlaying();
previousTrack();
break;
}
}
catch (Exception) {
//Debug.WriteLine(ex.Message);
}
}
void stopBeforePlaying() {
MediaPlayer player = BackgroundMediaPlayer.Current;
if (player != null)
player.Pause();
}
void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e) {
object foregroundMessageType;
if (e.Data.TryGetValue(ApplicationSettingsConstants.ChapterStatus, out foregroundMessageType)) {
//do something here
}
}
void UpdateUVCOnNewTrack() {
//update buttons here
}
async void playTrack() {
MediaPlayer player = BackgroundMediaPlayer.Current;
try {
if (...) {
//load track
player.Play();
}
else {
player.Pause();
MessageService.SendMessageToForeground(ApplicationSettingsConstants.ChapterStatus, (short)ChapterStatus.ForegroundFileNotFound);
}
}
catch (System.IO.DirectoryNotFoundException) {
player.Pause();
MessageService.SendMessageToForeground(ApplicationSettingsConstants.ChapterStatus, (short)ChapterStatus.ForegroundFileNotFound);
}
catch (System.IO.FileNotFoundException) {
player.Pause();
MessageService.SendMessageToForeground(ApplicationSettingsConstants.ChapterStatus, (short)ChapterStatus.ForegroundFileNotFound);
}
finally {
UpdateUVCOnNewTrack();
}
}
void nextTrack() {
//load next track
}
void previousTrack() {
//load previous here
}
}
Why I am getting the above error?
Note: I have followed Microsoft Sample Background Audio for Windows Phone 8.1 Sample to enable background audio player.
Thanks!
Some situations may cause this exception in BackgroundAudio.Reference to Windows-universal-samples/Samples/BackgroundAudio/cs/BackgroundAudio/Scenario1.xaml.cs, the comment of function ResetAfterLostBackground()
The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately, any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost..
So add this function, and invoke it where you catch the error.
const int RPC_S_SERVER_UNAVAILABLE = -2147023174; // 0x800706BA
private void ResetAfterLostBackground()
{
BackgroundMediaPlayer.Shutdown();
try
{
BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
}
catch (Exception ex)
{
if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
{
throw new Exception("Failed to get a MediaPlayer instance.");
}
else
{
throw;
}
}
}
I need to simulate the behaviour of the default camera midlet from Nokia.
It's for Nokia C6, and I am writing it in J2ME.
I use MMAPI, the problem is the size of VideoControl item, I made it videoControl.setDisplayFulscreen(true); but it ain't fullscreen at all, the method setDisplaySize doesn't help, the size of videoControl itself is roughly one third of the display (the rest of desired displaySize is just black), here's a code sample:
public CameraCanvas (Evidence_elektromeru midlet, ManagePhotos caller,String name) {
super(true);
this.midlet = midlet;
this.caller = caller;
this.name = name;
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://devcam0");
player.realize();
// player.prefetch();
if (videoControl2 != null)
videoControl2.setVisible(false);
videoControl1 = (VideoControl) player.getControl("VideoControl");
videoControl1.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,this);
videoControl1.setDisplayLocation(0, 0);
videoControl1.setDisplaySize(360,500);
}catch (MediaException me2) {
try {
videoControl1.setDisplayFullScreen(true);
} catch (Exception e) {}
}
catch (Exception e) {}
finally {
try {
player.start();
} catch (Exception e) {}
videoControl1.setVisible(true);
}
try to use
mCamera = Manager.createPlayer("capture://video");
mCamera.realize();
mCamera.prefetch();
or you can replace mCamera = Manager.createPlayer("capture://video"); by
mCamera = Manager.createPlayer("capture://image");
Hi I am new to android and I am learning by example. I am trying to make an activity that has a list view of all songs in my raw folder with media player controls at the bottom. I have everything working so far but I can't seem to get the SeekBar to stop force closing.
Here is the code:
public class music extends ListActivity implements Runnable {
private ArrayList<sound> mSounds = null;
private soundadapter mAdapter = null;
private ImageButton playbtn;
private SeekBar seekbar;
private int total;
private MediaPlayer mp = null;
private TextView selelctedFile = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
selelctedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setProgress(0);
// create a simple list
mSounds = new ArrayList<sound>();
sound s = new sound();
s.setDescription("Rudolph The Red Nosed Reindeer");
s.setSoundResourceId(R.raw.rudolphtherednosereindeer);
mSounds.add(s);
s = new sound();
s.setDescription("Battery");
s.setSoundResourceId(R.raw.battery);
mSounds.add(s);
mAdapter = new soundadapter(this, R.layout.listitem, mSounds);
setListAdapter(mAdapter);
playbtn = (ImageButton) findViewById(R.id.play);
playbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (mp.isPlaying()) {
mp.pause();
playbtn.setImageResource(android.R.drawable.ic_media_play);
} else {
mp.start();
playbtn.setImageResource(android.R.drawable.ic_media_pause);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
});
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id) {
sound s = (sound) mSounds.get(position);
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, s.getSoundResourceId());
selelctedFile.setText(s.getDescription());
playbtn.setImageResource(android.R.drawable.ic_media_pause);
mp.start();
total = mp.getDuration();
seekbar.setMax(total);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp.seekTo(progress);
seekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
Thread.sleep(100);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
// super.handleMessage(msg);
// txt.setText(Integer.toString(msg.what));
seekbar.setProgress(msg.what);
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
and here is the error i keep getting when i click several times on different songs:
04-14 02:53:00.452: W/dalvikvm(27452): threadid=19: thread exiting with uncaught exception (group=0x40018560)
04-14 02:53:00.466: E/AndroidRuntime(27452): FATAL EXCEPTION: Thread-22
04-14 02:53:00.466: E/AndroidRuntime(27452): java.lang.IllegalStateException
04-14 02:53:00.466: E/AndroidRuntime(27452): at android.media.MediaPlayer.getCurrentPosition(Native Method)
04-14 02:53:00.466: E/AndroidRuntime(27452): at net.cybercore.collapsingfromwithin.music.run(music.java:145)
04-14 02:53:00.466: E/AndroidRuntime(27452): at java.lang.Thread.run(Thread.java:1019)
Line error 145 is :
int currentPosition = mp.getCurrentPosition();
I cannot for the life of me figure out why it works for 3 or 4 times playing and then it kills the app.
Any help is appreciated. I have already looked at several other sites for examples including http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ and http://www.androiddevblog.net/android/playing-audio-in-android
**
UPDATE
**
I think I fixed it. thanks for your help I found Thread using for seekbar on android mediaplayer so i changed it to
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("My exeption" + e);
}
}
I still get the errors but they are not killing my app. I don't think this is right way to do it but its working.
You should prepare your media player when instanciating it.
A MediaPlayer object must first enter the Prepared state before playback can be started.
There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
Read it here
so you should call mp.prepare() after instanciating the player.
also you should make sure the media player in playing to run the run method. I'd start by adding
mp.isPlaying() to the while line.
while (mp != null && mp.isPlaying()) {
...
}
IllegalStateException means that you are on an illegal state to call that method, like for instance, if the player is stopped.
I'm not sure, but I think this will stop the run method when you pause the music. So you should try to avoid this. I create a boolean to identify that the player is playing or paused and use it on the while.