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.
Related
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 have songs from json in list view, and a play button in each row , after clicking on play Button my app freezes and App not responding dialog box comes, Sometime media player started after freezing sometimes its crashes. Because of App not responsive. This is my Code :
viewHolder.playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = position;
if (selectedPosition != mPlayingPosition) {
try {
mPlayerforplanet.reset();
mPlayerforplanet.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayerforplanet.setDataSource(song_urls);
logger.addRecordToLog("MediaPlayer audio session ID: " + mPlayerforplanet.getAudioSessionId());
logger.addRecordToLog("Media Player started " + "Started !");
mPlayerforplanet.prepare();
mPlayerforplanet.start();
} catch (IOException e) {
e.printStackTrace();
}
// playSongs(position);(i also try with method of playsong but no luck)
Toast.makeText(getContext(), "play song" + mPlayingPosition, Toast.LENGTH_SHORT).show();
}}});
Log cat after click on play button
01-10 07:13:33.501 17284-17293/luck.materialdesign.tabsnavigator I/art: Thread[5,tid=17293,WaitingInMainSignalCatcherLoop,Thread*=0xab8d8600,peer=0x12c000a0,"Signal Catcher"]: reacting to signal 3
01-10 07:13:34.273 17284-17293/luck.materialdesign.tabsnavigator I/art: Wrote stack traces to '/data/anr/traces.txt'
Please use prepareAsync instead of prepare and handle onPrepared and trigger start from there .
mPlayerforplanet.prepareAsync();
public void onPrepared(MediaPlayer mp) {
mPlayerforplanet.start;
}
sample code :
package com.example.simplemediaplayer.app;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.IOException;
public class MediaPlayerActivity extends ActionBarActivity {
private static final String TAG = "tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
String url = "http://www.brothershouse.narod.ru/music/pepe_link_-_guitar_vibe_113_club_mix.mp3"; // your URL here
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//mp3 will be started after completion of preparing...
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.media_player, 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);
}
}
For seek-bar use a anew runnable :
Starting runnable ,
public void onPrepared(MediaPlayer player) {
mPlayerforplanet.start();
mUpdateSeekBar.run();
}
Code in runnable
private final Runnable mUpdateSeekBar = new Runnable() {
#Override
public void run() {
int elapsedtime = mPlayerforplanet.getCurrentPosition();
/* update UI with getCurrentPosition*/
mHandler.postDelayed(mUpdateSeekBar, 1000);
}
};
I am trying to play an audio file from the internal storage.
The code I used is..
package com.abhi.firstapp.firstapp;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
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.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
File f= new File("/sdcard/a.mp3");
if(f.exists())
{
Toast toast= Toast.makeText(this, "file exists", Toast.LENGTH_LONG);
toast.show();
Log.d("uri","1");
Uri uri= Uri.fromFile(f);
Log.d("uri", "2");
mp= new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d("uri", "3");
try {
mp.setDataSource("/sdcard/a.mp3");
} catch (IOException e) {
e.printStackTrace();
}
//mp.setDataSource(getBaseContext(), uri);
Log.d("uri", "4");
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
Log.d("uri", "IOException");
}
mp.start();
}
else {
Toast toast1 = Toast.makeText(this, "file does not exist", Toast.LENGTH_LONG);
toast1.show();
}
//MediaPlayer mp= MediaPlayer.create(getBaseContext(), uri);
//mp.start();
}
#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);
}
}
By using the log, I can determine that this code is running till the mp.prepare(mediaplayer prepare). And on this step, it gives the error Illegal State Exception
Caused by: java.lang.IllegalStateException
at android.media.MediaPlayer.prepare(Native Method)
Please Help!
There are a couple of things you might want to change.
First: mp.prepare() will block your main thread, which is forbidden and will result in an exception where Android will close your app. To prevent this, mp.prepareAsync was designed. Use that method instead and implement both an onPreparedListener and an onErrorListener.
Second: you should provide a datasource before you call prepare().
You could do this for example this way:
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(streamURL);
} catch (IOException e) {
// Error, do something
}
mp.prepareAsync();
...
}
#Override
public void onPrepared(MediaPlayer player) {
mediaPlayer.start();
}
...
}
I had the same problem. It can be raised because MediaPlayer is already prepared. When you create a new MediaPlayer by MediaPlayer mp = MediaPlayer.create(getContext(),someUri); mp prepares automatically so you should not prepare it by yourself.
I get this error anytime i try to build my android project.
Error:(106, 99) error: incompatible types: >> cannot be converted to
android.support.v7.util.SortedList.Callback>
The app stream tracks from a playlist in soundcloud.
/*
* Copyright (c) 2015. Ukor
*/
package com.ukorjidechi.bethelcitymobile;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class BciRadio extends AppCompatActivity {
private static final String TAG = "MainActivity";
private List<Track> mListItems;
private SCTrackAdapter mAdapter;
private TextView mSelectedTrackTitle;
private ImageView mSelectedTrackImage;
private MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bci_radio);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
togglePlayPause();
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayerControl.setImageResource(R.drawable.ic_play);
}
});
mListItems = new ArrayList<Track>();
ListView listView = (ListView)findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(this, mListItems);
listView.setAdapter(mAdapter);
mSelectedTrackTitle = (TextView)findViewById(R.id.selected_track_title);
mSelectedTrackImage = (ImageView)findViewById(R.id.selected_track_image);
mPlayerControl = (ImageView)findViewById(R.id.player_control);
mPlayerControl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePlayPause();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Track track = mListItems.get(position);
mSelectedTrackTitle.setText(track.getTitle());
Picasso.with(BciRadio.this).load(track.getArtworkURL()).into(mSelectedTrackImage);
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
try {
mMediaPlayer.setDataSource(track.getStreamURL() + "?client_id=" + Config.CLIENT_ID);
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
});
SCService scService = SoundCloud.getService();
scService.getRecentTracks(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()), new Callback<List<Track> >() {
#Override
public void success(List<Track> tracks, Response response) {
loadTracks(tracks);
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error: " + error);
}
});
}
private void loadTracks(List<Track> tracks) {
mListItems.clear();
mListItems.addAll(tracks);
mAdapter.notifyDataSetChanged();
}
private void togglePlayPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mPlayerControl.setImageResource(R.drawable.ic_play);
} else {
mMediaPlayer.start();
mPlayerControl.setImageResource(R.drawable.ic_pause);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#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 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) {
Intent setting = new Intent(BciRadio.this, SettingsActivity.class);
startActivity(setting);
return true;
} else if (id == R.id.action_about){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Considering this code:
package com.radio.radiostar;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import java.io.IOException;
public class MainActivity extends Activity implements OnClickListener {
private final static String RADIO_STATION_URL = "http://178.32.137.180:8665/stream";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
};
I want to enable the background play, with a widget on notification bar like "apollo" or any other media player (with only play/pause button and the "x" to close streaming and background).
Can you help me, writing the code that I must use, and in which part of code?
Thanks in advance.
Fabio.
EDIT: I have deleted
if (player.isPlaying()) {
player.p();
From
#Override
protected void onPause() {
super.onPause();
}
And now works in background u.u
I only need to show the widget on notification bar :)
You want to play the stream while the app is minimized? Then you have to user the Service. You should move your code to the service. And you will be able to handle notification bar from the service as well.
When you do this, you will probably ask yourself "how can I now update the UI since the player is handled in the service". The answer to this is usage of BroadcastService where your Service will broadcast all important data (like timer ticks while stream is active) and your Activity has to catch those data and use it to fill its own UI.
Since the code for what I described here is huge, you should try implementing a service and broadcast logic first, and if you are stuck, come back here with a concrete question.