I'm in the process of building a prototype for a project. I want to be able to stream music from my website to the app.
Here is what I have so far. Trying it with an m3u because I honestly have no idea what else to use for this.
Button buttonPlay;
Button buttonStop;
MediaPlayer mPlayer;
String url = "http://www.*******.com/*****/files.m3u";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Illegal Argument", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Security ", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Illegal Statement", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Prepare Illegal State", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Prepare IO", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
});
buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
}
}
});
Them problem is it throws IOexception after prepare. Now I read somewhere you have to download m3u files and then read them line by line. If that is the case, is there a better way? I'm attempting to make sort of a radio app for testing purposes that will play songs at random, not in order, so I don't want to hard code them MP3 files,
you cant just prepare a stream because it needs to download asynchronously. you will need to do this
Button buttonPlay;
Button buttonStop;
MediaPlayer mPlayer;
String url = "http://www.*******.com/*****/files.m3u";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Illegal Argument", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Security ", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Illegal Statement", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mPlayer.start();
}
};);
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Prepare Illegal State", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly! Prepare IO", Toast.LENGTH_LONG).show();
}
}
});
buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
}
}
});
Related
When I click on the play button again and again, it plays multiple times simultaneously. I want to stop multiple playing. Here's the code:
Objects for Media player and buttons
MediaPlayer mPlayer;
Button playbtn;
Button stopbtn;
Button click event listener to play audio
playbtn = (Button) findViewById(R.id.play);
playbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri myUri1 = Uri.parse("file:///sdcard/Birds/parrot.mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(getApplicationContext(), myUri1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
Button click event listener to stop audio
stopbtn = (Button) findViewById(R.id.stop);
stopbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mPlayer!=null && mPlayer.isPlaying()){
mPlayer.stop();
}
}
});
any help would be appreciated. Thanks!
It is creating a new player with every play click but only keeping the reference to the last player so the solution is to keep player in a list and stop all.
private List<MediaPlayer> players = new ArrayList<>()
stopbtn = (Button) findViewById(R.id.stop);
stopbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
for(player in players){
if(player!=null && player.isPlaying()){
mPlayer.stop();
}
}
players.clear();
}
});
Another solution is, only use one instance of player. move the player initialization outside click as:
playbtn = (Button) findViewById(R.id.play);
Uri myUri1 = Uri.parse("file:///sdcard/Birds/parrot.mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(getApplicationContext(), myUri1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
playbtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(!mPlayer.isPlaying())
mPlayer.start();
I am trying to stream audio files in android but everytime I get this exception
java.io.IOException: Prepare failed.: status=0x1
for my songs url stored on the server. eg(http://Touchstoneesol.com/listen/ML1 (Section 2).mp3);
But same code stream this link properly (http://android.programmerguru.com/wp-content/uploads/2013/04/hosannatelugu.mp3);
Now I am stuck inbetween whether there is some problem in the code or my songs link is corrupt.
buttonPlay = (Button) findViewById(R.id.play);
buttonPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
});
public class StreamAudioDemo extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {
MediaPlayer mp;
ProgressDialog pd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt = (Button)findViewById(R.id.play);
bt.setOnClickListener(this);
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("StreamAudioDemo", "prepare finished");
pd.setMessage("Playing.....");
mp.start();
}
#Override
public void onClick(View v) {
try
{
pd = new ProgressDialog(this);
pd.setMessage("Buffering.....");
pd.show();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setDataSource("http://www.robtowns.com/music/blind_willie.mp3");
mp.prepareAsync();
mp.setOnCompletionListener(this);
}
catch(Exception e)
{
Log.e("StreamAudioDemo", e.getMessage());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
pd.dismiss();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
pd.dismiss();A
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
}
}
This is the xml that contains the button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stream Audio and Play"
android:id="#+id/play"
/>
</LinearLayout
I have searched and researched stackoverflow and google but can't find any answer to MY question. I've found other question and answers but that were related to sounds saved in the app but I'm creating an app which gets data from Parse server, so it gets mp3 files and display these in listview and than when an item is clicked it plays that track. But here comes the problem: When you play a sound and click on another one, the first just doesn't stop and the second starts to play.
I have tried with the following code but it's just not working.
Here's my code:
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final MediaPlayer mediaPlayer = new MediaPlayer();
final MediaPlayer scndmediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
scndmediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mediaPlayer.isPlaying()) {
Toast.makeText(getContext(), "First is playing", Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
scndmediaPlayer.setDataSource(audioFileURL);
scndmediaPlayer.prepare();
scndmediaPlayer.start();
//soundtoolbar.setTitle(name);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
if (scndmediaPlayer.isPlaying()){
scndmediaPlayer.stop();
}
Toast.makeText(getContext(), "First is starting", Toast.LENGTH_SHORT).show();
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
soundtoolbar.setTitle(name);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() || scndmediaPlayer.isPlaying()) {
mediaPlayer.pause();
scndmediaPlayer.pause();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_play_arrow_white_24dp));
} else {
mediaPlayer.start();
scndmediaPlayer.start();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_pause_white_24dp));
}
}
});
}
});
I've created 2 mediaplayers with the code above and when user clicks the play button it first checks if any of the player is running.
I'm trying to achieve the following: When user clicks the play button it checks if the (1st) mediaPlayer is running or not. If it's running, it has just to stop it and launch (2nd) scndmediaPlayer or viceversa... if second is playing it stops that and launch first one. so it will create a loop: 1st is playing? User clicks another button stop first. Launch second. User clicks another button. First is playing? No. Second is playing? Yes. Stop the second and launch the first.
But can't find where is the problem in my code.
Please help me with this. I'm trying to resolve it from 2 days but I'm unable...
Thanks :)
EDIT: I tried using one MediaPlayer and do the following: Check if mediaplayer is playing! No it isn't playing. Start it. User clicks the button again and it stops the mediaplayer and start it with new audioFileUrl. BUT. MediaPlayer is forgetting that it's playing. Seems like it just starts the track and than forget and to check if it's true i set a Toast: when mediaplayer isn't playing the toast shows and it's showing every time I click a track in the list which means it forget that it has a track which is playing...
EDIT 2: I managed to do the following: It plays the track. User clicks another track. It stops the mediaplayer but doesn't play the new track. User click once again. It plays the new track. User clicks the new track and the app crashes...
EDIT 3: Posting my entire class:
public class MyAdapter extends ParseQueryAdapter<ParseObject> {
public Button playPause, next, previous;
public Toolbar soundtoolbar;
boolean isPlaying = false;
public MyAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MyClass");
query.orderByDescending("createdAt");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, final ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_audio_files_item, null);
}
super.getItemView(object, v, parent);
final Button play = (Button) v.findViewById(R.id.play);
playPause = TabFragment1.playPause;
next = TabFragment1.next;
previous = TabFragment1.previous;
soundtoolbar = TabFragment1.soundtoolbar;
final ParseFile descr = object.getParseFile("audiofile");
final String name = object.getString("name");
final String audioFileURL = descr.getUrl();
final SlidingUpPanelLayout slidingUpPanelLayout = TabFragment1.spanel;
play.setText(name);
final MediaPlayer mediaPlayer = new MediaPlayer();
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying != true) {
Toast.makeText(getContext(), name+" is playing", Toast.LENGTH_SHORT).show();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
soundtoolbar.setTitle(name);
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
mediaPlayer.start();
isPlaying = true;
}
});
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e2) {
e2.printStackTrace();
} catch (IllegalStateException e3) {
e3.printStackTrace();
} catch (IOException e4) {
e4.printStackTrace();
} catch (NullPointerException e5) {
e5.printStackTrace();
}
} else {
mediaPlayer.stop();
Toast.makeText(getContext(), "Starting "+name, Toast.LENGTH_SHORT).show();
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
soundtoolbar.setTitle(name);
slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (SecurityException e2) {
e2.printStackTrace();
} catch (IllegalStateException e3) {
e3.printStackTrace();
} catch (IOException e4) {
e4.printStackTrace();
} catch (NullPointerException e5){
e5.printStackTrace();
}
}
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_play_arrow_white_24dp));
} else {
mediaPlayer.start();
playPause.setBackground(getContext().getDrawable(R.drawable.ic_pause_white_24dp));
}
}
});
}
});
return v;
}
}
Somebody please help...
i suggest you to checkout SoundPool . İt ll helps you. And one more , may be you ll put media urls to array or something like this.And use one mediaPlayer By the way, you ll avoid from two mediaPlayer and avoid from memory leak.
http://developer.android.com/reference/android/media/SoundPool.html
My app needs to implement audio capture function .
i have followed several tutorials and google guides . so i have made the code below.
it works fine until the second attempt. when i capture my voice once, it 's able to reply what i have said.
in the second attempt, when i think it had to over write the file created, the app crashes. probably i ignore some methods.
could you help me ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizializzaView();
Media();
SetListner();
}
public void inizializzaView(){
Text=(TextView)findViewById(R.id.textview);
Registra=(Button)findViewById(R.id.bottonereg);
Ascolta=(Button)findViewById(R.id.bottoneascolta);
Stop=(Button)findViewById(R.id.bottonestop);
Stop.setEnabled(false);
Ascolta.setEnabled(true);
}
public void SetListner(){
Registra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start(v);
}
});
Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop(v);
}
});
Ascolta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play(v);
}
});
}
public void Media(){
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recording.3gp";;
// android voice recorder
media = new MediaRecorder();
media.setAudioSource(MediaRecorder.AudioSource.MIC);
media.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
media.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
media.setOutputFile(outputFile);
}
public void start(View view){
try {
media.prepare();
media.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Registra.setEnabled(false);
Stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stai registrando Burlone !!!", Toast.LENGTH_LONG).show();
}
public void stop(View view){
media.stop();
media.release();
media = null;
Stop.setEnabled(false);
Registra.setEnabled(true);
Toast.makeText(getApplicationContext(), "Registrazione Terminata",
Toast.LENGTH_LONG).show();
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
myPlayer.release();
Ascolta.setEnabled(true);
Stop.setEnabled(false);
Toast.makeText(getApplicationContext(), "Ascolta.......",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i've solved !!!.
the code needs to be implemented .
public void start(View view){
try {
Media();// this creates a new object whenever you capture new voice.
media.prepare();
media.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Registra.setEnabled(false);
Stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stai registrando Burlone !!!", Toast.LENGTH_LONG).show();
}
public void stop(View view){
media.stop();
media.release();
media = null;
Stop.setEnabled(false);
Registra.setEnabled(true);
Toast.makeText(getApplicationContext(), "Registrazione Terminata",
Toast.LENGTH_LONG).show();
}
I have an activity which has a series of buttons which when pressed should play an audio file. I have been trying to implement this using MediaPlayer however I cant get it to work.
Here is the code I have been trying:
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.setDataSource(this, R.raw.greet_1);
mp.prepare();
mp.start();
}
});
The setDateSource method doesnt seem to work, can anyone tell me where I am going wrong?
I would like to then set the mediaPlayer to the relevant audio file based on which button is pressed, is this possible?
Updated
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Uri myUri = Uri.parse(R.raw.greet_1);
mp.setDataSource(GreetingsLesson.this, R.raw.greet_1);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
try this:
final MediaPlayer mp = new MediaPlayer();
Button ger1play = (Button) findViewById(R.id.ger1play);ger1play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp.setDataSource(CurrentActivity.this, R.raw.greet_1);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Ifyou want to send the media player object with one of the files fromapplication raw resources or from application assets files you can dothat as follows:
try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.greet_1);
mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mp.start();
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
Why not just use
mp = MediaPlayer.create(this, R.raw.greet_1);
Then you don't need the prepare or start.
Are you running this in an emulator? If so check your AVD manager has under hardware, the property "Audio playback support | yes" added