What's wrong with this audio stream playing code for Android? - android

I have a problem with this code for live streaming:
package cm.ex.wwd;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
public class AudioStream extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://www.songblasts.com/songs/hindi/t/three-idiots/01-Aal_Izz_Well-(SongsBlasts.Com).mp3";
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(url);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
mp.start();
} catch (Exception e) {
Log.i("Exception", "Exception in streaming mediaplayer e = " + e);
}
}
}

url you are giving is not a valid one.it is showing 404 NOT FOUND.so it is creating problem for you.give a valid one

Without knowing the exact problem it is difficult to answer. If you do this on your UI Thread you might also run into an application crash as the call to prepare() might take to long. Better use prepareAsync() and the associated listeners when using streaming.
As mentioned before, also the URL gives a 404.

i have done little changes in above code. check out this one.
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
#Override
public void onPrepared(MediaPlayer play) {
play.start();
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}

Related

OnCompletionListener - App Stops from Working

I am using a method to initialize and prepare a MediaPlayer (defined as class variable). It takes a String which is the name of the song as its parameter and it sets the DataSource to that particular path.
public void create_and_prepare_song(String x) {
if (mp != null)
mp.release();
mp = new MediaPlayer();
String filePath = Environment.getExternalStorageDirectory().getPath() + "/songsfolder/" + x + ".mp3";
try {
mp.setDataSource(filePath);
} catch (IOException e) {
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();
}
}
Now, somewhere inside my code I use this method to initialize and prepare "1.mp3". Then, as soon as this song is finished, I use an onCompletionListener so that "2.mp3" is played after, and "3.mp3" then. I use:
create_and_prepare_song("1");
i = 2;
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (i <= 3) {
String int_to_String = i + "";
create_and_prepare_song(int_to_String); //1
mp.setOnCompletionListener(this);
mp.start();
i++;
}
}
});
mp.start();
Now, this causes app to stop from working! However, if I just copy and paste the body of the method to the //1 line instead, the app works fine, playing first, second and third song. Why is that so? Thanks a lot
Note that you are creating a new player inside of create_and_prepare_song() but the old one is still referenced inside of the listener.
That's because the global variable and the onCompletion parameter has the same name: mp.
Here's piece of code that works:
package com.example.simon.mplaylist;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import java.io.IOException;
/**
* Created by Simon on 2014 Jul 20.
*/
public class MainActivity extends Activity {
static int currentSong;
static MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mediaPlayer != null)
return;
currentSong = 1;
create_and_prepare_song(currentSong);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (currentSong++ >= 3) {
mediaPlayer = null;
return;
}
create_and_prepare_song(currentSong);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
});
mediaPlayer.start();
}
public void create_and_prepare_song(int songNum) {
if (mediaPlayer != null)
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
String storage = Environment.getExternalStorageDirectory().getPath();
String filePath = storage + "/songsfolder/" + String.valueOf(songNum) + ".mp3";
try {
mediaPlayer.setDataSource(filePath);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE also that I defined the MediaPlayer as static and also am checking # onCreate for it's presence. That way you avoid multiple songs playing at once if the activity is recreated (e.g. screen rotation).
You really shouldn't be starting actual playback inside create_and_prepare_song(). It should be started inside onPrepared() since there might be some delay from the call to prepare() and the media being ready to play.

Android MediaPlayer returning error (1, -1004) when trying to play some streams

As it says in the title when trying to stream from some streams like this one:
http://173.192.137.34:8050
LogCat throws error (1, -1004) which is translated to:
MEDIA_ERROR_IO: File or network related operation errors.
At the same time, this small sample can play many other streams.
Is it because of stream type or something else?
package com.example.strm;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
public class EntryActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
InitializeStream();
} catch (Exception e) {
e.printStackTrace();
}
}
private void InitializeStream() throws Exception{
String url = "http://173.192.137.34:8050";
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
}
}
I ran into a similar problem. For me it was that HTTP basic authentication was required for some streams (streams over https). Even though I was using:
SharedPreferences shared_prefs = getApplicationContext().getSharedPreferences("***_prefs", 0);
final String username = shared_prefs.getString("username", null);
final String password = shared_prefs.getString("password", null);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
video_view.setVideoURI(Uri.parse(enclosure_url));
to authenticate, authentication was not actually occurring during setVideoURI. I had to insert the basic HTTP authentication credentials between the protocol and the domain name:
// in this app, only https urls required authentication, your logic may differ
if (enclosure_url.contains("https")) {
SharedPreferences shared_prefs = getApplicationContext().getSharedPreferences("***_prefs", 0);
final String username = shared_prefs.getString("username", null);
final String password = shared_prefs.getString("password", null);
enclosure_url = enclosure_url.replaceFirst("https://", "https://"+username+":"+password+"#");
}
video_view.setVideoURI(Uri.parse(enclosure_url));
replace
mediaPlayer.prepareAsync();
with
mediaPlayer.prepare();
I Hope this Code will Help you
MediaPlayer mediaPlayer = new MediaPlayer();
player.setAudenter code hereioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setOnInfoListener(this);
player.setOnPreparedListener(this);
player.setOnSeekCompleteListener(this);
player.setOnVideoSizeChangedListener(this);/*
player.setWakeMode(getApplicationContext(),PowerManager.PARTIAL_WAKE_LOCK);*/
try {
player.setDataSource(this, Uri.parse(url));
player.setOnPreparedListener(myContext);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Android playing audio and recordning audio at the same time

How to record audio and playing sound at the same time. Which process is better to implement in background and what to use Thread or AsyncTask? I haved tried playing sound in new thread and recordning on main thread but i have problem that on some devices i get error that the main thread is overload.
Is it better to use native rocordning, because i also need recorded buffer?
Does anybody have any example how to use native recording?
You can use following custom class:-
package com.app.controller;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.provider.SyncStateContract.Constants;
import android.widget.Toast;
public class MediaController implements OnPreparedListener{
public MediaController() {
// TODO Auto-generated constructor stub
}
public MediaPlayer mp;
public void getMediaPlayObject() {
try {
System.out.println("00000000000000");
mp = new MediaPlayer();
System.out.println("2222222222");
} catch (Exception e) {
// TODO: handle exception
System.out.println("exception in audia player====" + e.toString());
}
}
public void onPrepared(MediaPlayer player) {
mp.start();
}
boolean WORKING = true;
public void mediaPlayStart(final Context m_Context) {
try {
mp = new MediaPlayer();
mp.setDataSource(m_Context, Uri.parse(Contants.audioURL_OR_PATH));
mp.prepare();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setLooping(true);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(m_Context, "Service unavailable this time. Please try again!", Toast.LENGTH_LONG).show();
System.out.println("#####THE EXCEPTION IN THE MEDIA PLAYER PLAY==="+e.getMessage());
}
}
public void mediaPlayStop() {
try {
if (mp.isPlaying()) {
mp.stop();
}
} catch (Exception e) {
// TODO: handle exception
}
}
private static String getSoundPath(int countPositiong) {
// TODO Auto-generated method stub
String aa = "";
try {
if (countPositiong < 10) {
aa = "sounds/00" + countPositiong + ".mp4";
} else if (countPositiong < 100) {
aa = "sounds/0" + countPositiong + ".mp4";
} else {
aa = "sounds/" + countPositiong + ".mp4";
}
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("name is : " + aa);
return aa;
}
}

Working with MP3 sound in Processing for Android ( need to stop )

I am developing an app for Android devices using Processing 2.0, now I have playMP3(); function but need to stop the sound using stopMP3();. I tried everything but what is the best way to load an mp3 and play/stop using processing?, snd.stop(); within the stopMP3 function does not work...
import android.media.*;
import android.content.res.*;
...
MediaPlayer snd;
...
void setup()
{
MediaPlayer snd = new MediaPlayer();
}
...
void playMP3()
{
try {
AssetManager assets = this.getAssets();
AssetFileDescriptor fd = assets.openFd("loop1.mp3");
snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
snd.prepare();
snd.start();
snd.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void stopMP3(){
????
}
this is a simple sample for media player
private MediaPlayer m_Player;
//Start Play Function
private void startPlaying() {
m_Player = new MediaPlayer();
m_Player.setOnCompletionListener(onComplete);
try {
if(m_Player.isPlaying())
stopPlaying();
m_Player.setDataSource(m_FileName);
m_Player.prepare();
m_Player.start();
} catch (IOException e) {
}
}
//Stop Play Function
private void stopPlaying() {
m_Player.stop();
m_Player.reset();
m_Player = null;
}
//and this is onComplete Listener
MediaPlayer.OnCompletionListener onComplete = new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stopPlaying();
}
};
i hope it's helping you

Media Player called in state 0, error (-38,0)

I am currently trying to design a simple app that streams an internet radio station. I have the URL for the station and am setting up the Media Player like
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
The program isn't crashing when emulated, but nothing is playing and I am get the following error:
start called in state 0
and right below it is
Error (-38,0)
Does anyone know what this means?
I've read a little about these state errors, but couldn't find anything that applies to my project.
You need to call mediaPlayer.start() in the onPrepared method by using a listener.
You are getting this error because you are calling mediaPlayer.start() before it has reached the prepared state.
Here is how you can do it :
mp.setDataSource(url);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
player.start();
}
It seems like Error -38 means a state-exception (as the error-message indicates). For example if you call start(), before the song was ready, or when you call pause(), even if the song isn't playing at all.
To fix this issue check the state of the mediaPlayer before calling the methods. For example:
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
Additionally, the MediaPlayer is sending event-messages. Even if you do not need the prepared-event (although it would be a good idea to not start the playback before this event was fired) you must set a callback-listener. This also holds true for the OnErrorListener, OnCompletionListener, OnPreparedListener and OnSeekCompletedListener (if you call the seek method).
Listeners can be attached simply by
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Do something. For example: playButton.setEnabled(true);
}
});
I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.
This is my code,tested and working fine:
package com.example.com.mak.mediaplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mpp = MediaPlayer.create(this, R.raw.red); //mp3 file in res/raw folder
Button btnplay = (Button) findViewById(R.id.btnplay); //Play
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vone) {
mpp.start();
}
});
Button btnpause = (Button) findViewById(R.id.btnpause); //Pause
btnpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vtwo) {
if (mpp.isPlaying()) {
mpp.pause();
mpp.seekTo(0);
}
}
});
}
}
I encountered the same issue few days ago. My audio MediaPlayer works fine on devices with high processing power, but for slow devices, the media player just did not play some time and from LogCat it had many complain about called in wrong state. So I resolved it by calling putting the call to start(), pause(),... in onPrepared() method of OnPreparedListener() as below:
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
........
mediaPlayer.start();
....
songControlBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
............
}
});
}
});
Also try to release any media player that you do not need any more. For example, if you do not want to play the audio or video on background then you should call mediaPlayer.release() in onPause().
i tested below code. working fine
public class test extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
#Override
public void onPrepared(MediaPlayer play) {
play.start();
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
Some times file are encoded in a way that Android can't decode. Even some mp4 files can not be played. Please try a different file format (.3gp are played most of the time) and see..
You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.
Therefore you should always register an error handler to catch those things (as #tidbeck suggested).
At first, I advice you to take a look at the documentation for the MediaPlayer class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States
In my example it was the method mediaPlayer.CurrentPosition, that I called while the media player was in a state, where it was not allowed to call this property.
above the picture,you can get the right way.
I solved both the errors (-19,0) and (-38,0) , by creating a new object of MediaPlayer every time before playing and releasing it after that.
Before :
void play(int resourceID) {
if (getActivity() != null) {
//Using the same object - Problem persists
player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
After:
void play(int resourceID) {
if (getActivity() != null) {
//Problem Solved
//Creating new MediaPlayer object every time and releasing it after completion
final MediaPlayer player = MediaPlayer.create(getActivity(), resourceID);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
player.release();
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
}
if(length>0)
{
mediaPlayer = new MediaPlayer();
Log.d("length",""+length);
try {
mediaPlayer.setDataSource(getApplication(),Uri.parse(uri));
} catch(IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(length);
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
It was every much frustrated. So, I got solution which works for me.
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(file.getAbsolutePath());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
});
}
});
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
For me this worked
mp.seekTo(0);
mp.start();
I also got this error i tried with onPreparedListener but still got this error. Finally i got the solution that error is my fault because i forgot the internet permission in Android Manifest xml. :)
<uses-permission android:name="android.permission.INTERNET" />
I used sample coding for mediaplayer. I used in StreamService.java
onCreate method
String url = "http://s17.myradiostream.com:11474/";
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mp = new MediaPlayer();
AssetFileDescriptor afd = mContext.getAssets().openFd(fileName);
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepareAsync();
I have change setAudioStreamType to setAudioAttributes;
mediaPlayer.setAudioAttributes(AudioAttributes.Builder()
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.setLegacyStreamType(AudioManager.STREAM_ALARM)
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
I am new in android programming and i had same error as this one. so i simply redefined the mp.createmediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI). It may not the true way to do it but it worked fined for me:
try {
mp = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
} catch (Exception e) {
e.printStackTrace();
}
mp.start();

Categories

Resources