sorry my english, but I'm from Brazil and I used the google translator.
Well, I'm struggling in this application where I am trying to make a streaming an online radio, works fine in version 2.2, but version 4.0 does not work. No error occurs, simply does not work. Below is my code.
I appreciate any help.
package com.radiomiriam;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity {
public String url = "http://69.64.48.96:9880";
public MediaPlayer player = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void stop(){
Toast.makeText(getApplicationContext(), "Finalizando...", Toast.LENGTH_SHORT).show();
if(player.isPlaying()){
player.stop();
}
}
public void play(){
if(player.isPlaying()){
Toast.makeText(getApplicationContext(), "Já está em execução!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Preparando...", Toast.LENGTH_SHORT).show();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
player.setDataSource(url);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
}
}
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
play();
break;
case R.id.btnStop:
stop();
break;
}
}
}
Hello, excuse my insistence but I still have not found the solution to my problem and do not know how to solve, I have once again asking for your help to solve this problem.
The application runs in versions 2.x and 3.x but not in version 4.x. Below is a link to download the project, to which you can take a look and help me.
http://nsi.inf.br/RadioMiriam.rar (removed)
i downloaded your project and it actually returns error Code:
E/MediaPlayer( 1976): error (-38, 0)
It is caused by starting mediaplayer before it is prepared.
I have made few changes and it started to work. You should :
Set onPrepared listener on MediaPlayer (i.e. in onCreate)
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Remove player.start() from your play() method
Set datasource in this way (in your play() method)
player.setDataSource(this, Uri.parse("http://69.64.48.96:9880/"));
It works on my HTC Sensation with Android 4.0.3
If you need any assistance please let me know.
EDIT: i forgot, i also removed
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
It is redundant
The prepare() call is probably blocking the UI thread (which android 4.0 hates it when you do that)
You will need to this work in a background thread like an asynctask. Here is a anonymous version of implementing AsyncTask to run play() in the background.
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... voids) {
play();
return null;
}
}.execute();
break;
case R.id.btnStop:
stop();
break;
}
}
You will need to read up a bit about MediaPlayer's states (playing, preparing, stopped, etc) to learn why calling prepare will block the UI thread (
for more info on AsyncTasks
You haven't set any link between buttons in your .xml file and your code. onClick method is never called even though you are pressing the buttons.
Replace your onCreate method with this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.btnPlay);
playButton.setOnClickListener(this);
Button stopButton = (Button) findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
play();
}
It is always better in android to do any IO work on a background thread.
And that includes MediaPlayer . but in MediaPlayer case you already have prepareAsync() method to prepare the MediaPlayer in the background for you.
A good way to do that is like this:
package com.radiomiriam;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class Main extends Activity implements OnPreparedListener{
public String url = "http://69.64.48.96:9880";
public MediaPlayer player = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void stop(){
Toast.makeText(getApplicationContext(), "Finalizando...", Toast.LENGTH_SHORT).show();
if(player.isPlaying()){
player.stop();
}
}
public void play(){
if(player.isPlaying()){
Toast.makeText(getApplicationContext(), "J? est? em execuç?o!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Preparando...", Toast.LENGTH_SHORT).show();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
player.setDataSource(url);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.btnPlay:
play();
break;
case R.id.btnStop:
stop();
break;
}
}
}
Also it is always a good practice to read the documentations, so here is a link to MediaPlayer API : MediaPlayer
Related
To start off, playing and stopping music works fine. I've already searched SX, and have tried some of the solutions listed for this issue, but they haven't resolved my issue.
I have a "Replay Music" button, that is supposed to restart an .mp3 file from the beginning. I've got the necessary code in place (like reset(), prepare(), etc, in order for the media player to replay the music, but when the button is pushed, nothing happens.
I have all the OnClickListeners and other necessary things setup, it is just this one issue.
Below is the complete code for my "Replay Music" method. Any help will be gratefully received.
Just a thought: Perhaps it is something to do with the placement of the mediaPlayer.start() method call?
public void replaySoundButtonListener() {
Button testButton = (Button) findViewById(R.id.replayMusicButton);
testButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource("sdcard/InsomniMusic/insomnimix.mp3");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
You only need to prepare and set the data source of a mediaplayer once. When you call reset the mediaplayer has to be reinitialised completely (set datasource again and call prepare). If you would like to reset the mediaplayer to the start of the song I guess you could use
mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
If the song has already ended (or stopped otherwise), only mediaPlayer.start() will suffice (but I guess in your case you can never be sure of that).
More information on the start function here
I made a functions to start() stop() reset() and pause() in another Class
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer extends MediaPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer!=null)
{
mPlayer.release();
mPlayer=null;
}
}
public void pause()
{
if(mPlayer.isPlaying()) {
mPlayer.pause();
}
else
{
mPlayer.start();
}
}
public void reset(Context c)
{
stop();
mPlayer=MediaPlayer.create(c, R.raw.one_small_step); //uzimamo .create(context,..) jer uzimamo iz res/raw lokalne datoteke
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
public void play(Context c)
{
stop();
mPlayer=MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
}
//Here is my fragment
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
private Button mResetButton;
private AudioPlayer mPlayer=new AudioPlayer();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=getActivity().getLayoutInflater().inflate(R.layout.fragment_hello_moon, container);
mPlayButton=(Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.play(getActivity());
}
});
mStopButton=(Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.stop();
}
});
mPauseButton=(Button)v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.pause();
}
});
mResetButton=(Button)v.findViewById(R.id.hellomoon_resetButton);
mResetButton.setOnClickListener(new OnClickListener(
) {
#Override
public void onClick(View v) {
mPlayer.reset(getActivity());
}
});
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
mPlayer.stop(); //Nakon sto je fragment unisten MediaPlayer nastavlja radit jer je na drugacijem Threadu pa treba pozvati Stop();
}
Streaming MediaPlayer not working on Samsung galaxy s3. Don't have device myself but getting reports of it not working. Also tried Remote Test Lab and does not work. I have tested on many other devices and all work excepted for s3. Any help would be awesome!
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
Toast.makeText(this, "Just one moment please", Toast.LENGTH_LONG).show();
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://************";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
This is what I do to get a streaming music to play, just tested this on a Samsung Galaxy SIII and it is working fine. The audio stream in this is a public university radio stream. But this should work with other online streams. Just make sure you enable the internet permissions in your manifest.
public class MainActivity extends Activity {
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("http://streams.tsc.usu.edu:8888");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.start();
}catch(Exception e){
e.printStackTrace();
}
}
This might be a little late, but for those who are coming to this looking for this answer, one solution might be to implement the MediaPlayer.OnPreparedListener.
public class MyActivity extends Activity implements MediaPlayer.OnPreparedListener
MediaPlayer mpMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
try{
mpMediaPlayer = new MediaPlayer();
mpMediaPlayer.setDataSource("audio url");
mpMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpMediaPlayer.prepare();
mpMediaPlayer.setOnPreparedListener(this);
}catch(Exception e){
e.printStackTrace();
Log.e(TAG, "Error loading media");
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mpMediaPlayer.start();
}
GOAL: Start, Stop, then Start play of a sound by clicking button 3 times
Hello All
I am new to Android.
I have had trouble restarting the play of a sound after stopping it by click of a button.
I have researched this problem
( Link ) and found different methods to apply.
So, I have tried four ways (unsuccessfully) to do this.
There are four buttons which use different methods.
Button 1 will be used as a control.
Look to comments for results of different methods.
I will post a couple entries from LogCat below.
Thank You
Here is a link to a relevant Android State Diagram
src/com.example.playsound/MainActivity.java
package com.example.playsound;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
//Create Media Player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button Sound
final MediaPlayer mPlayer1 = MediaPlayer.create(MainActivity.this, R.raw.playsound0);
final MediaPlayer mPlayer2 = MediaPlayer.create(MainActivity.this, R.raw.playsound1);
final MediaPlayer mPlayer3 = MediaPlayer.create(MainActivity.this, R.raw.playsound2);
final MediaPlayer mPlayer4 = MediaPlayer.create(MainActivity.this, R.raw.playsound3);
//Button References
Button button1 = (Button)this.findViewById(R.id.button1);
Button button2 = (Button)this.findViewById(R.id.button2);
Button button3 = (Button)this.findViewById(R.id.button3);
Button button4 = (Button)this.findViewById(R.id.button4);
//Button 1 OnClickListener
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer1.isPlaying() ) {
try {
mPlayer1.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
// BUTTON 1
else { // plays sound upon first click, stops on second click
try { // but does not play on third click
mPlayer1.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
});
//Button 2 Uses .prepareAsync()
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer2.isPlaying() ) { // BUTTON 2
try { // Plays sound upon first click, stops on second click
mPlayer2.stop(); // But will not play upon third click
mPlayer2.reset();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
else {
try {
mPlayer2.prepareAsync();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mPlayer2.start();
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer3.isPlaying() ) {
try { // BUTTON 3
mPlayer3.stop(); // Does not play sound upon first button click
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
else {
mPlayer3.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mPlayer3) {
mPlayer3.start();
}
});
}
}
});
//Button 4 OnClickListener
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer4.isPlaying() ) {
try {
mPlayer4.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
// BUTTON 4
else { // does not play sound on first click
try {
mPlayer4.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer4.start();
}
}
});
}
}
Most errors in LogCat are similar to:
prepareAsync called in state 8
start called in state 0
start called in state 1
The errors are mostly "call in state #" errors.
I have referenced the diagram posted in the link above.
I still have these errors when I attempt to call methods in correct place.
You are calling methods in unappropriate states.
PrepareAsync can be called in only {Initialized, Stopped} state.
Start can be called only in {Prepared, Started, Paused, PlaybackCompleted} states.
So if you try to call those in other states than those then it will throw exception.
To have a clear knowledge about the states read this doc
first of all, I'm starting yesterday on Android programming. I'm making a String, and in each selection I wanna play diferent sound. Ok, i've got the one, but in the other selection play the same sound because I don't know how to do it; maybe a Switch with different cases? thanks
now I have this code.`
import android.app.ListActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class sonidos extends ListActivity {
public String[] frases = {
"cake",
"butter",
"apple",
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, frases));
}
public void onListItemClick(ListView parent, View v){
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.sonidos);
}
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
}
If you use sound from assets folder you could use something like this:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd;
try {
switch(id)
{
case 1: afd = getAssets().openFd("cake.mp3"); break;
case 2: afd = getAssets().openFd("butter.mp3"); break;
default : afd = getAssets().openFd("apple.mp3"); break;
};
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
} catch (IOException e) {
e.printStackTrace();
SM.Exception("## Exception playing sound!");
}
if (player.isPlaying()) {
player.stop();
}
else {
try {
player.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
Hope this helps.
You need to write something like this:
public void onListItemClick(ListView parent, View v, long id){
MediaPlayer sound = null;
switch (id) { // argument 'id' is the row of the clicked item
case FIRST_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.dtrain);
break;
case SECOND_ROW:
sound = MediaPlayer.create(sonidos.this, R.raw.bell);
break;
// and so on ...
}
if (sound.isPlaying()) {
sound.stop();
} else {
try {
sound.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now.
if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound.
here's my code
public class ProjectisengActivity extends Activity{
ImageButton mainkan;
MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
i'm create for android 3.0 (HoneyComb)
try below code in go function....
public void go() {
if(mp == null) {
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
}
It is simple, you should follow these steps to achieve this.
In your test2.xml create two buttons name start and stop.
Set the android:visibility attribute gone of stop button in xml file.
Now in your activity get the id of these two buttons and write the code for
starting and stopping of media player.
Set the visibility attribute gone on start click and visible of stop button,
follow its opposite on stop click.
I think you have wrong this line :
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
You create new instance every time user clicks the button, so it's never playing and starts again. Put this line into onCreate rather than go()
Try also this,
public class MainActivity extends Activity {
MediaPlayer mPlayer;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (flag == 0) {
Log.v("Inside if", "Success" + "");
mPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.sample);
mPlayer.start();
flag++;
} else {
Log.v("Inside else", "Success" + "");
mPlayer.stop();
mPlayer.release();
flag = 0;
}
}
});
}
}