I've created an app (radio streaming) but doesn't works on S4.
I've tested this app on my Galaxy Nexus, Xperia Arc s, Htc Desire and it works properly.
I think there is an error in my code.
My code:
package com.dieesoft.radiolluvia;
import java.io.IOException;
import android.R.array;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.TrackInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
private ProgressDialog pb;
private Button bplay;
private Button bstop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bplay = (Button) findViewById(R.id.button1);
bstop = (Button) findViewById(R.id.button2);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
bplay.setOnClickListener(this);
bstop.setOnClickListener(this);
}
#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;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.button1 )
{
//button play
new iniciarStreaming().execute();
Toast.makeText(this, "Play", Toast.LENGTH_SHORT).show();
}
else if(v.getId() == R.id.button2)
{
//button stop
Toast.makeText(this, "Stop", Toast.LENGTH_SHORT).show();
mp.stop();
}
}
private class iniciarStreaming extends AsyncTask<Void, Void, Boolean> implements OnPreparedListener
{
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
mp.setDataSource("http://makrodigital.com:8134/radiolluvia");
} 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();
}
mp.prepareAsync();
mp.setOnPreparedListener(this);
return null;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
pb = new ProgressDialog(MainActivity.this);
pb.setMessage("Buffering...");
pb.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
if (pb.isShowing()) {
pb.cancel();
}
mp.start();
}
}
Your streaming url (http://makrodigital.com:8134/radiolluvia) has AAC format with content-type: audio/aacp.
But audio/aacp streaming is not supported directly. Maybe previously was another link? MP3 or something else?
For playing this url you can use this library:
http://code.google.com/p/aacplayer-android/
Related
I'm developing a simple chat app and it just stops after transmitting the message. The Server shows the message that means that it is sent successfully but my app crashes after that. This is the Client code :
package com.example.androidpc;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Chat extends Activity {
Socket socket;
EditText msg_txt;
TextView chatfield_tv;
Button send_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
msg_txt = (EditText) findViewById(R.id.msg_txt);
chatfield_tv = (TextView) findViewById(R.id.chatfield_tv);
send_btn = (Button) findViewById(R.id.send_btn);
socket = SocketWrapper.getSocket();
send_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new chatIO().execute();
}
});
}
private class chatIO extends AsyncTask<String,String,String>{
PrintStream ps;
Scanner scan;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
ps = new PrintStream(socket.getOutputStream());
ps.println(msg_txt.getText().toString());
publishProgress("you");
scan = new Scanner(socket.getInputStream());
publishProgress("i");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
if(values[0].equals("you"))
{
chatfield_tv.append("You : "+msg_txt.getText().toString());
msg_txt.setText("");
}
else
{
chatfield_tv.append("Server : "+scan.nextLine());
}
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
ps.flush();
scan.close();
super.onPostExecute(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have retrieved the songs present on my phone and when I click on the list item it switches to the next activity and plays the song.
But when I go back to my playlist and click again on another song, the previous song is still being played as well as the song I just clicked.
Here is the code of Playlist.java:
package com.example.padyplayer;
import java.io.IOException;
import java.util.ArrayList;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Playlist extends Activity implements OnItemClickListener {
ListView tracks_view;
ArrayList<String> songs;
ArrayAdapter<String> songs_items;
//MediaPlayer mediaplayer;
//AudioManager audiomanager;
Cursor cursor;
Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
tracks_view = (ListView) findViewById(R.id.tracks);
generate_Playlist();
songs_items = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, songs);
//mediaplayer = new MediaPlayer();
//audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
tracks_view.setAdapter(songs_items);
tracks_view.setOnItemClickListener(this);
}
#SuppressWarnings("deprecation")
private void generate_Playlist() {
// TODO Auto-generated method stub
uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String projection[] = { android.provider.MediaStore.Audio.Media.DATA,
android.provider.MediaStore.Audio.Media.TITLE,
android.provider.MediaStore.Audio.Media.ARTIST,
android.provider.MediaStore.Audio.Media.ALBUM,
android.provider.MediaStore.Audio.Media.DURATION };
cursor=this.managedQuery(uri, projection, null, null, null);
songs=new ArrayList<String>();
while(cursor.moveToNext())
{
songs.add(cursor.getString(1));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.playlist, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
//cursor.moveToPosition(position);
int index1=position;
Intent i=new Intent(getApplicationContext(),Controls.class);
i.putExtra("index", index1);
startActivity(i);
}
}
Here is the second class Controls.java:
package com.example.padyplayer;
import java.io.IOException;
import java.util.ArrayList;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Controls extends Activity implements OnClickListener {
TextView song_view,artist_view;
Button play,next,back;
MediaPlayer mediaplayer=new MediaPlayer();
AudioManager audiomanager;
ArrayList<String> songs;
Cursor cursor;
Uri uri;
private int index=0;
//ArrayAdapter<String> song_items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controls);
play=(Button)findViewById(R.id.play);
next=(Button)findViewById(R.id.next);
back=(Button)findViewById(R.id.back);
play.setOnClickListener(this);
next.setOnClickListener(this);
back.setOnClickListener(this);
//mediaplayer=new MediaPlayer();
audiomanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
getMusic();
Bundle b=getIntent().getExtras();
index = b.getInt("index");
playSong(index);
}
#SuppressWarnings("deprecation")
private void getMusic() {
// TODO Auto-generated method stub
uri=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String projection[]={android.provider.MediaStore.Audio.Media.DATA,
android.provider.MediaStore.Audio.Media.TITLE,
android.provider.MediaStore.Audio.Media.ARTIST,
android.provider.MediaStore.Audio.Media.ALBUM,
android.provider.MediaStore.Audio.Media.DURATION};
cursor=this.managedQuery(uri, projection, null, null,null);
songs=new ArrayList<String>();
while (cursor.moveToNext()) {
songs.add(cursor.getString(1));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.controls, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.play:
if(mediaplayer.isPlaying())
{
mediaplayer.pause();
play.setText("play");
}
else if(mediaplayer!=null)
{
mediaplayer.start();
play.setText("pause");
}
break;
case R.id.next:
if(index<(songs.size()-1)){
index+=1;
playSong(index);
}
else
{
index=0;
playSong(index);
}
break;
case R.id.back:
if(index>0){
index-=1;
playSong(index);
}
else
{
index=songs.size()-1;
playSong(index);
}
break;
default:
break;
}
//
}
private void playSong(int index2) {
// TODO Auto-generated method stub
cursor.moveToPosition(index2);
int song_id=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String song_name=cursor.getString(song_id);
try {
mediaplayer.reset();
mediaplayer.setDataSource(song_name);
mediaplayer.prepare();
mediaplayer.start();
} 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();
}
}
}
I'm stuck with this problem since two days. Please help.
My advice: use a Service to host the MediaPlayer and have your Activities communicate with the Service to play and stop songs. Don't forget to call release on the MediaPlayer when you are done (if you use a new player for the next song).
Edit:
The Activity is not going to be the same instance each time it opens, and you create a new MediaPlayer each time an instance of the Activity is created. Underneath the hood, there is a native object actually playing the music that is not intrinsically tied to the life cycle of the Activity, and you aren't calling stop or pause anywhere that would get called when Activities are changed. You could potentially stop and release the MediaPlayer in an appropriate callback (onPause or onDestroy), but that will prevent you from playing music continuously. If you insist on using an Activity to host the MediaPlayer, then music playback has to be completely integrated into the life cycle of the Activity. When the Activity is changed, you need to stop and release its resources explicitly. If you put it in a Service, you won't have that limitation. You can manage one or more MediaPlayers (note the setNextMediaPlayer method) without them being tied to any particular Activity.
it will keep playing. You need to free your media player object when you press back button. In onPause(), release your media player object otherwise it will keep playing.
To implement music player, you can refer open source code. Refer VLC player source code.
before start playing song every time mMediaPlayer.reset() from that you can play new song every time or check if mediaplayer is playing or not if playing stop it
This is what the code looks like, logcat keeps stating "start called in state 0"
I tried different ways to start the video. What am I missing? I also tried a OnPreparedListener but it kept giving me the same errors.
package com.example.videoplaybacktests;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
String stringPath = "/drawable/visource.mp4";
public String RTSP = "rtsp://v2.cache7.c.youtube.com/CjYLENy73wIaLQkFPOlBtC4qExMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYJeOw_HjwJ6bUQw=/0/0/0/video.3gp";
public Uri vidURI = Uri.parse(RTSP);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pausing = false;
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepare();
} catch (IllegalArgumentException 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();
}
mediaPlayer.start();
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(pausing){
pausing = false;
mediaPlayer.start();
}
else{
pausing = true;
mediaPlayer.pause();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
You can not call start without the mediaPlayer being prepared! Thats the reason you get the error
Use prepareAsync instead
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException 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();
}
and start playback on onPrepared():
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
If it still doesnt start on onVideoSizeChanged
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mediaPlayer.start();
}
package com.example.videoplaybacktests;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
MediaPlayer mediaPlayer;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean pausing = false;;
String stringPath = "/drawable/visource.mp4";
public String RTSP = "rtsp://v2.cache7.c.youtube.com/CjYLENy73wIaLQkFPOlBtC4qExMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYJeOw_HjwJ6bUQw=/0/0/0/video.3gp";
public Uri vidURI = Uri.parse(RTSP);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPauseVideo = (Button)findViewById(R.id.pausevideoplayer);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(RTSP);
mediaPlayer.prepare();
} catch (IllegalArgumentException 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();
}
}});
buttonPauseVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mediaPlayer==null)
return;
else if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}else{
mediaPlayer.start();
}
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
I have an imageview and button in the xml file . loading the image1 and play song1.mp3 file.when the song is over it should load next image and play the song2.mp3 song it should go on until the last image. button for closing and exit the application.
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
public class MainActivity extends Activity {
public MediaPlayer mpp;
final int image[] = {R.drawable.apple,R.drawable.ball,R.drawable.cat};
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView img = (ImageView) findViewById(R.id.img);
String audio[]={"song1.mp3","song2.mp3","song3.mp3"};
AssetFileDescriptor descriptor;
try {
descriptor = getAssets().openFd(audio[i]);
mpp.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(),descriptor.getLength());
descriptor.close();
mpp.prepare();
mpp.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
img.setImageResource(image[i]);
i++;
mpp.start();
}
});
} }
Fatal Exception in main.RuntimeException not able to start the activity
new android dev hopeful here. I've been attempting to implement an app that, upon holding down the "ok" button, it will play the default ringtone in a loop.
What I have so far
package com.tick.helloAndroid;
import net.technologichron.android.control.NumberPicker;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
//import android.widget.TextView;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;
public class main extends Activity implements OnTouchListener {
private int REQUEST_ENABLE_BT = 1;
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the window layout
setContentView(R.layout.main);
final Button zero = (Button) this.findViewById(R.id.ok);
zero.setOnTouchListener(this);
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp.setDataSource(this, alert);
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
case MotionEvent.ACTION_UP:
mp.pause();
}
return true;
}
}
From doing some searching on SO, this seems to work for some people, however, the line
mp.setDataSource(this, alert);
seems to not work. By not work, I mean that it forces an "Unhandled Exception Error", which upon doing a try-catch statement,
try {
mp.setDataSource(this, alert);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "args", Toast.LENGTH_LONG).show();
finish();
return;
} catch (SecurityException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "sec", Toast.LENGTH_LONG).show();
finish();
return;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "illega", Toast.LENGTH_LONG).show();
finish();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "io", Toast.LENGTH_LONG).show();
finish();
return;
}
compiles without any error but crashes when I try to run the app on the android emulator, it does not print any of the above catches' strings.
Any thoughts and ideas about what I have done incorrectly will be most appreciated.
edit: could it be from the fact that the emu does not have a ringtone?
forgot to instantiate mp....hahahahha