App not Responding While Playing media from url - android

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);
}
};

Related

Android MP3 Player, play/pause button not working

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.

Recording and saving audio file without replacing another

I'm developing an android app which has a record feature. I'm able to record and save the audio file into my device's storage, however there seems a problem. When I record twice, the recorded audio replaces the first recorded one.
I want my app to do like this:
I recorded and it has successfully recorded and saved the audio
file into the storage;
I recorded again and has successfully recorded and saved the audio
file into the storage;
There would be two recorded and saved audio files in the storage.
Here is the code I'm using:
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class RecordModule extends Activity {
Button SpeakBtn, StopBtn;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordmodule);
SpeakBtn = (Button) findViewById(R.id.SpeakBtn);
StopBtn = (Button) findViewById(R.id.StopBtn);
StopBtn.setEnabled(false);
SpeakBtn.setEnabled(true);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
SpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SpeakBtn.setEnabled(false);
StopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
StopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
StopBtn.setEnabled(false);
SpeakBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
}
});
}
#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_record_module, 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);
}
The first recording is being overwritten, so the others need to have another file name.
I would suggest you to use output file name as the time when the record was created:
Date createdTime = new Date();
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + createdTime + "_rec.3gp";

Android Audio not playing from server

I am playing an audio (.mp3) from the server url using the following Android code. But, it is not playing the audio, simply does nothing, no errors. I have set Android min 11 to 22. I am testing on 5.0.2 Android phone. Could someone help what could be the reason not playing, please?
UPDATED:
I have solved it now. I converted google drive url to google drive download url using the help this link, and able to play the audio well.
http://www.labnol.org/internet/direct-links-for-google-drive/28356/
Code
package com.bclradio.manket.bclfm;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.media.MediaPlayer;
import android.media.AudioManager;
import java.io.IOException;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Context;
public class BCLFMActivity extends Activity {
final Context context = this;
static final String AUDIO_PATH =
"https://drive.google.com/open?id=0BzcFuGIeWflwMmlITExmY3BCck0&authuser=0";
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bcl_fm);
}
public void doClick(View view) {
switch (view.getId()) {
case R.id.PlayStopButton:
Log.e("FMApp", "Play button clicked");
//AlertDialog.Builder ab = new AlertDialog.Builder(context);
//ab.setMessage("Test").show();
try {
playAudio(AUDIO_PATH);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
private void playAudio(String url) throws Exception
{
killMediaPlayer();
Log.e("FMApp", "Play Audio function triggered");
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
killMediaPlayer();
}
private void killMediaPlayer() {
if(mediaPlayer!=null) {
try {
mediaPlayer.release();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
#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_bcl_fm, 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);
}
}
Look at these two tutorials, In these the .mp3 files are playing through web url,
Example of streaming mp3 mediafile from URL with Android MediaPlayer class
Play Mp3 file from a Url
Also if you want to play .mp3 file in background I think you have to use Service and AIDL for it,
Look at basic Android-Music Player demo MusicDroid - Audio Player Part II it describe how to use Service and AIDl for your Audio Player.
Thanks..
Check out this answer.

Sound cannot be played

I create a simple project with one layout that contains two buttons, and this is my code:
package com.example.tessound;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener
{
MediaPlayer player;
Button play,mute;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button1);
play.setOnClickListener(this);
mute = (Button)findViewById(R.id.button2);
mute.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;
}
public void onClick(View view)
{
if(view.getId()==R.id.button1)
{
playSound(1);
}
else if(view.getId()==R.id.button2)
{
playSound(2);
}
}
public void playSound(int arg)
{
if (arg == 1)
{
player = MediaPlayer.create(this, R.raw.atur);
}
else if (arg == 2)
{
player = MediaPlayer.create(this, R.raw.back);
}
if(player != null)
{
player.setLooping(false);
player.start();
}
try
{
if(player != null)
{
if (player.isPlaying())
{
player.stop();
player.release();
}
}
}
catch(Exception e)
{
}
}
}
When I tried to click the button the sound doesn't play.
Following the logic for your playSound method with an argument value of 1:
1) arg == 1 so:
player = MediaPlayer.create(this, R.raw.atur);
2) player has been set so is not null, hence:
player.setLooping(false);
player.start();
3) Then it's your try block. player is not null and is playing, hence:
player.stop();
player.release();
So I think you are starting the playback and then immediately stopping it. I imagine you should only execute the try/catch code if the method does not receive a valid argument, i.e. it should be an 'else' of the preceding 'if' statement.
EDIT:
Looking at this again, I think the try/catch code should go at the top of the method. It will then stop the player and release it (if it is in use) before trying to start playing a new sound. Logically that makes sense.
Use Log to trace the control and find the error !
Log.e("AnyTAG","Description of the Log");
your code seems fine!

Latency in playing a .wav/.mp3/.ogg audio file in Android App

I'd written an application for playing 20 millisecond audio clip(.wav format).
It simply plays the sound clip repeatedly 1000 times.
But due to Latency, number of times it plays lies between 978 and 984. I'd also tried other audio format(.ogg, .mp3, etc).
I want reduce the latency and also to get reliable number.
I'm sharing my code below:
package com.abhinav.soundlooper;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button btnStart;
TextView tvPause, tvLoop;
EditText etPause, etLoop;
long pause, loop;
private CountDownTimer timer;
MediaPlayer mp;
public Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
// tvLoop = (TextView) findViewById(R.id.etLoop)
etPause = (EditText) findViewById(R.id.etPause);
etLoop = (EditText) findViewById(R.id.etLoop);
btnStart.setOnClickListener(this);
mp = MediaPlayer.create(getApplicationContext(), R.raw.beepwav);
}
#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 onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
// pause = Integer.valueOf(etPause.getText().toString()) + 1 ;
// loop = 1 + Integer.valueOf(etLoop.getText().toString());
// long ti = (pause+30);
// long tt = ti*loop;
timer = new CountDownTimer(30000, 30) {
int i =0;
public void onTick(long millisUntilFinished) {
// v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
mp.start();
// try {
// timer.wait(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
i++;
}
public void onFinish() {
// mTextField.setText("done!");
Log.i("loop", ""+i);
stopAll();
// mp.stop();
// mp.release();
}
}.start();
//
}
protected void stopAll() {
// TODO Auto-generated method stub
timer.cancel();
}
}
I'm not sure but if 1000 milliseconds is 1 second. So 30,000 milliesconds is 30 seconds.
and if the audio is 20 milliseconds then 30,000/20 is 1,500. So the audio is capable of being played 1.5K in 30 seconds.
timer = new CountDownTimer(30000, 27) {
int i =0;
public void onTick(long millisUntilFinished) {
// v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
mp.start();
// try {
// timer.wait(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
i++;
}
if with the 30 latency it's 950 times, what happens if we lower the latency to about 27?
and you can always you if statement ..
if (i == 1000){
stopAll();
} else {
i++
}

Categories

Resources