I'm new to android and I need it for a project I'm working on. I need it to play a sound by clicking a button. I followed online tutorials but my code does not play sounds at all and I'm getting an error on MediaPlayer Error(-19,0). I've tried a lot of the fixes I saw here and I can't seem to make it work. Any help? Here's the code
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioManager audioManager = (AudioManager) getSystemService(MainActivity.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
Button buttonHello = (Button) findViewById(R.id.button1);
buttonHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = Medi aPlayer.create(MainActivity.this, R.raw.button);
mp.start();
mp.setOnCompletionListener(new OnCompletion Listener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
}
});
} catch (Exception e) {
System.out.println("Error!");
}
}
#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;
}
}
This links http://marakana.com/forums/android/examples/59.html has the great example to use MediaPlayer class to play song from raw folder.
To play song from files in the memory you can use the following code.
MediaPlayer mp = new MediaPlayer();
mp.reset();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filename.getAbsolutePath());
Uri selectedImage=RingtoneDownload.this.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
mp.setDataSource(RingtoneDownload.this,selectedImage);
mp.prepare();
mp.start();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This code is working for me while set the source from file.
Related
I'm following an Udemy class on making a MP3 player like Spotify. I'm new to Android studio, and know/understand very little. The class is a bit older, and uses an older version of Android Studio from 2 years ago, so this might be part of the problem. I can hear the MP3 when I first start debugging, and the button will also change from play to pause, however, it is unresponsive to any clicking. I hear the sound it's been clicked, but it never changes status or pauses the audio. Thank you for the assistance, it's greatly appreciated!
***************** Main Activity.java ************************
package live.regionradio.regionradio;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.media.MediaPlayer;
import java.io.IOException;
import android.media.AudioManager;
public class MainActivity extends AppCompatActivity {
static FloatingActionButton btnPlayPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnPlayPause = (FloatingActionButton) findViewById(R.id.fab);
btnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
String url = "https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3";
if (Player.player == null)
new Player();
Player.player.playStream(url);
}
public static void flipPlayPauseButton (boolean isPlaying) {
if (isPlaying) {
btnPlayPause.setImageResource(android.R.drawable.ic_media_pause);
}
else {
btnPlayPause.setImageResource(android.R.drawable.ic_media_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.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
***************** Player.java ************************
package live.regionradio.regionradio;
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.util.Log;
import java.io.IOException;
public class Player {
MediaPlayer mediaPlayer = new MediaPlayer();
public static Player player;
String url = "";
public Player() {
this.player = this;
}
public void playStream(String url) {
if (mediaPlayer != null) {
try {
mediaPlayer.stop();
} catch (Exception e) {
}
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
private MediaPlayer mp;
#Override
public void onPrepared(MediaPlayer mp) {
this.mp = mp;
playPlayer();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
private MediaPlayer mp;
#Override
public void onCompletion(MediaPlayer mp) {
this.mp = mp;
MainActivity.flipPlayPauseButton(false);
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pausePlayer () {
try {
mediaPlayer.pause();
MainActivity.flipPlayPauseButton(false);
}
catch (Exception e) {
Log.d("EXCEPTION", "Failed to pause media player.");
}
}
public void playPlayer () {
try {
mediaPlayer.start();
MainActivity.flipPlayPauseButton(true);
}
catch (Exception e) {
Log.d("EXCEPTION", "Failed to play media player.");
}
}
public void togglePlayer () {
try {
if (mediaPlayer.isPlaying())
pausePlayer();
else
playPlayer();
}
catch (Exception e){
Log.d("Exception", "failed to toggle media player.");
}
}
}
public void onClick(View view) {
}
I believe this is exactly what happens after you click the button, namely - nothing. You should put something inside that function. You override the onClick function and leave it empty, so anything you would want to happen after clicking, you should put inside it.
Your "togglePlayer()" is never used, perhaps that's what you should put in the listener.
I wanna make "Play/Stop" button. When button "Play" is clicked, the song must be played and its text should be converted into "Stop" and when "Stop" is clicked, the button text should be changed into "Play" again and song should start again to play from the beginning.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button btn_playStop;
private MediaPlayer mediaPlayer;
private boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Play Music");
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.zara_sa);
btn_playStop = (Button)findViewById(R.id.btn_play_stop);
btn_playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() && flag==true){
stopSong();
}
else if (flag == false){
playSong();
}
}
});
}
public void playSong(){
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
public void stopSong() {
mediaPlayer.stop();
btn_playStop.setText("Play");
flag = false;
}
}
You must call mediaPlayer.prepare(); if you called mediaPlayer.stop(); so in the first time you can just call mediaPlayer.start(); but in the next times you should call mediaPlayer.prepare(); before mediaPlayer.start();
public void playSong(){
try {
mediaPlayer.prepare();
} catch (IOException e) {
}
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
I am new bee to android. I have some about 120 audio files, which I want to store in database and then on different button clicks the audio files will retrieve which I want to play. I don't know how to do this. I have searched several links but unable to find help. I have little knowledge of SQLite database, any help will be appreciated.
here is my code , I have now only one audio file saved in assets folder.
If this can help.
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyButtonsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MediaPlayer mp = new MediaPlayer();
Button c = (Button)findViewById(R.id.btnstop);
Button b = (Button)findViewById(R.id.btnplay);
c.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(mp.isPlaying())
{
mp.stop();
}
}
});
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("audio/001s-ff.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
One thing more , where should I save my 100+ audio files? In assets folder manually or in database? which way will be more light in size?
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
I am trying to create a RTSP player for Android, but I am getting the error Video Can't be played. I don't know whats the mistake I am making, this is simply not working, I tried all methods, I am giving the code below
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
VideoView myVideoView;
ProgressDialog progDailog;
AudioManager audio;
MediaController mediaController;
String unStringUrl="rtsp://his.dvrdns.org:8554/channel/2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myVideoView = (VideoView)findViewById(R.id.videoplayer);
progDailog = ProgressDialog.show(MainActivity.this, null, "Video loading...", true);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mediaController = new MediaController(this);
myVideoView.setMediaController(mediaController);
myVideoView.setVideoURI(Uri.parse(unStringUrl));
myVideoView.requestFocus();
myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
// called too soon with rtsp in 4.1
if(progDailog != null) {
progDailog.dismiss();
}
myVideoView.start();
}
});
myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
/*Intent intent = new Intent(MyVideoView.this, lastActivity);
intent.putExtra("cleTitre", activityTitle);
intent.putExtra("cleSegment", activityCat);
startActivity(intent);*/
}
});
myVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
if(progDailog != null) {
progDailog.dismiss();
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You can try including internet -Permisison line in (following line) in your app's Manifest File.In my case it worked.
uses-permission android:name="android.permission.INTERNET"
Hope this helps.