Recording and saving audio file without replacing another - android

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";

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.

how to create Crete new file every time when the button presses?

I just have only basic knowledge about android. today i developed one audio recording application, but the problem is user can record audio and it can play the audio, when it runs the second time(or user press the record button again) the newly recorded file replaces withe the old file from the storage, i want create new file for each and every recording operations , how to do that ?
this is my main activity
package com.hackerinside.jaisonjoseph.sample_recorder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
record=(Button)findViewById(R.id.record);
stop.setEnabled(false);
play.setEnabled(false);
outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording.mp3";
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputfile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException ise){
}catch (IOException ioe){
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
record.setEnabled(true);
myAudioRecorder.release();
myAudioRecorder=null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource(outputfile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(),"playing audio",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
// here
}
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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_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);
}
}
On your record button click use this line
outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+System.currentTimeMillis()+".mp3";
If you give same file name, the file will be override the old one.
Use Calendar.getInstance().getTimeInMillis() to create unique files name for each recording.
outputfile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+ Calendar.getInstance().getTimeInMillis()+".mp3";
Also create one function to create new audio file and initialise recorder with new file reference.
private void prepareNewRecording() {
outputfile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+ Calendar.getInstance().getTimeInMillis()+".mp3";
myAudioRecorder=newMediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputfile);
}
Now call above function from start recording
prepareNewRecording();
myAudioRecorder.prepare();
myAudioRecorder.start();

how to Make file in particular folder?

i just created a audio recording application, when it creates new audio file i want it to be there in a particular folder (here sample)
this is how i am making the file
outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+System.currentTimeMillis()+".mp3";
and this is the folder i created for newly files
File directory=new File(Environment.getExternalStorageDirectory()+separator+"sample");
directory.mkdirs();
whenever the application creates new files it should automatically go to the sample folder
i am a beginner in android , those who can help me,please provide the code too, thanks
here is my main activity
package com.hackerinside.jaisonjoseph.sample_recorder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import static java.io.File.separator;
public class MainActivity extends AppCompatActivity {
private Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
record=(Button)findViewById(R.id.record);
stop.setEnabled(false);
play.setEnabled(false);
File directory=new File(Environment.getExternalStorageDirectory()+separator+"jaison");
// directory.mkdirs();
outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+System.currentTimeMillis()+".mp3";
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setOutputFile(outputfile);
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException ise){
}catch (IOException ioe){
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
record.setEnabled(true);
myAudioRecorder.release();
myAudioRecorder=null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource(outputfile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(),"playing audio",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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_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);
}
}
File directory=new File(Environment.getExternalStorageDirectory(),"sample");
if(!directory.exists())
{
if(!directory.mkdirs())
{
Toast ( could not create directory: + directory.getAbsolutePath());
return;
}
}
File file = new File(directory, "recording_"+System.currentTimeMillis()+".mp3");
This code does not create a file. Only a File object. But you can use the File object file to create a file.
Since sample is the default directory,
String fileName = "/recording_" + System.currentTimeMillis() + ".mp3";
final private String directory = Environment.getExternalStorageDirectory()+ "/sample";
Create the directory if doesn't exist.
if(!new File(directory).exists()){
if(!file.mkdir()){/*error*/ }
}
Now, the new file path
String outputfile = directory + "/" + fileName;
I got the answer Thanks everyone ,for helping
File directorysample=new File(Environment.getExternalStorageDirectory()+separator+"sample");
directorysample.mkdirs();
String filename = "/recording_" + System.currentTimeMillis() + ".mp3";
final String directory = Environment.getExternalStorageDirectory()+ "/sample";
outputfile = directory + "/" + filename;

Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I just have only basic knowledge about android. today i developed one audio recording application, but the problem is user can record audio , stop the recording and it can play the audio,but after playing when the user press the record button again the app is crashing , anyone can help me?
this is my main activity
package com.hackerinside.jaisonjoseph.sample_recorder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
record=(Button)findViewById(R.id.record);
stop.setEnabled(false);
play.setEnabled(false);
outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording_"+System.currentTimeMillis()+".mp3";
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.DEFAULT);
myAudioRecorder.setOutputFile(outputfile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException ise){
}catch (IOException ioe){
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
record.setEnabled(true);
myAudioRecorder.release();
myAudioRecorder=null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer=new MediaPlayer();
try {
mediaPlayer.setDataSource(outputfile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(getApplicationContext(),"playing audio",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
// here
}
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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_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);
}
}
Try adding this
myAudioRecorder=new MediaRecorder();
in your
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
myAudioRecorder=new MediaRecorder();
myAudioRecorder.prepare();
myAudioRecorder.start();
}
Alternatively u can remove myAudioRecorder.release(); from stop button click.
it should be released during onPause() on your activity
That is because, you are setting it null while stopping mediaRecorder
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
record.setEnabled(true);
myAudioRecorder.release();
myAudioRecorder=null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(),"recorded audio",Toast.LENGTH_LONG).show();
}
});
When you click again on record this will got executed,
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
// myAudioRecorder is null when you come up second time.
// Initialize myAudioRecorder to prevent an exception.
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException ise){
} catch (IOException ioe) {
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(),"record startded",Toast.LENGTH_LONG).show();
}
});
myAudioRecorder.prepare(); will through NullPointerException as myAudioRecorder is null. Although above code is in try.. catch but you did not catch NullPointerException, App will crash.
if you look at documentations it says you don't have access to recorder after you releasd it which is what you are doing when you press stop,you have to instantiate new recorder or simply don't release it.

App not Responding While Playing media from url

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

Categories

Resources