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 made an app which uses a MediaRecorder and a MediaPlayer, but whenever I record something and play it, it kinda loops back on itself.
e.g I say, one, two, three, four, five, six, seven, eight, nine, ten
but it plays back as one, two, three three, four four, five five five etc. it gets worse if the recording is longer?
It might be a simple bug, but I don't see it.
Here is my code :
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Switch switchPlay;
Button btnRecord, btnDelete;
ProgressBar pBarMetronome;
MediaRecorder mRecorder1, mRecorder2, mRecorder3, mRecorder4, mRecorder5, mRecorder6;
MediaPlayer mp1, mp2, mp3, mp4, mp5, mp6;
String sdPath = "/sdcard/Looper Recordings/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchPlay = (Switch)findViewById(R.id.switchPlay);
btnRecord = (Button)findViewById(R.id.buttonRecord);
btnDelete = (Button)findViewById(R.id.buttonDelete);
pBarMetronome = (ProgressBar)findViewById(R.id.progressBarMetronome);
clearFile();
createFile();
lineOne();
}
private void playOne(){
mp1 = new MediaPlayer();
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}
private void recordOne(){
mRecorder1 = new MediaRecorder();
mRecorder1.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder1.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder1.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder1.setOutputFile(sdPath+"one.mp3");
//mRecorder1.setAudioEncoder(MediaRecorder.getAudioSourceMax());
mRecorder1.setAudioEncodingBitRate(16);
mRecorder1.setAudioSamplingRate(44100);
try {
mRecorder1.prepare();
Toast.makeText(MainActivity.this, "preparing...", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "starting...", Toast.LENGTH_SHORT).show();
mRecorder1.start();
new CountDownTimer(5000,1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
mRecorder1.stop();
Toast.makeText(MainActivity.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}.start();
}
private void lineOne(){
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recordOne();
}
});
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(4000,1000){
#Override
public void onTick(long millisUntilFinished) {
btnRecord.setText(""+(millisUntilFinished/1000));
playOne();
}
#Override
public void onFinish() {
}
}.start();
}
});
switchPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//ON
}else{
//OFF
}
}
});
}
private void clearFile(){
File dir = new File(Environment.getExternalStorageDirectory()+"/sdcard/Looper Recordings");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
}
private void createFile(){
File recordingDirectory = new File(Environment.getExternalStorageDirectory()+ File.separator+"Looper Recordings");
if(!recordingDirectory.exists() && !recordingDirectory.isDirectory())
{
// create empty directory
if (recordingDirectory.mkdirs())
{
Toast.makeText(MainActivity.this, "Folder for recordings created!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Folder for recordings could not be created?", Toast.LENGTH_SHORT).show();
}
}
else
{
}
}
}
I know it's very messy but I'm still prototyping
Thanks to anyone who is willing to help!
It seems you are initializing MediaPlayer multiple times and play them simeltenously
Did you try set looping false.
private void playOne(){
if(mp1 != null && mp1.isPlaying()){
{
mp1.stop();
}
mp1 = new MediaPlayer();
mp1.setLooping(false);
Uri myUri = Uri.parse("/sdcard/Looper Recordings/one.mp3");
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp1.setDataSource(getApplicationContext(), myUri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp1.prepare();
Toast.makeText(MainActivity.this, "preparing", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
mp1.start();
Toast.makeText(MainActivity.this, "play!", Toast.LENGTH_SHORT).show();
}
I am trying to write code in Android to play music. But i am starting the music in a thread so music is breaking and i need to play the music in thread because i have receive the music name through a Bluetooth socket.
So , the thread will keep listening the socket , to get the updated Music file name. But while playing the music it's breaking and not playing properly.
MyCode:
package com.example.musicexample;
import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button btnPlay;
MediaPlayer mPlayer;
Thread canThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
canThread = new Thread(new Runnable() {
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
MainActivity.this.runOnUiThread(new Runnable()
{
public void run()
{
if(mPlayer.isPlaying()){
mPlayer.stop();
mPlayer.reset();
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a);
}
mPlayer.start();
}
});
}
}
});
canThread.start();
}
});
} }
This is the above code , please let me know , how can i play the music properly in a Thread?
mp3 pauses when on screen lock..here is my main java code...I've searched some information but nothing helped me.And by the way After clicking Play, then stop, then back to play, the application force crashes, sometimes it requires more clicks, sometimes fewer..Can someone help me please..Thank you !
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;
public class Main extends Activity implements OnClickListener {
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.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("http://users1.jabry.com/mine/inna.mp3");
} 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();
}
}
}
When the screen is locked your onPause is being called, and you are explicitly stopping the player there.
I could not resolve this media player error which says "stop called in state 1".my media player actually delays for few seconds before moving on to the next music.can anyone help me.
this might help u...
package com.commonsware.android.audio;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class AudioDemo extends Activity
implements MediaPlayer.OnCompletionListener {
private ImageButton play;
private ImageButton pause;
private ImageButton stop;
private MediaPlayer mp;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play=(ImageButton)findViewById(R.id.play);
pause=(ImageButton)findViewById(R.id.pause);
stop=(ImageButton)findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
setup();
}
#Override
public void onDestroy() {
super.onDestroy();
if (stop.isEnabled()) {
stop();
}
}
public void onCompletion(MediaPlayer mp) {
stop();
}
private void play() {
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
private void stop() {
mp.stop();
pause.setEnabled(false);
stop.setEnabled(false);
try {
mp.prepare();
mp.seekTo(0);
play.setEnabled(true);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void pause() {
mp.pause();
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(true);
}
private void loadClip() {
try {
mp=MediaPlayer.create(this, R.raw.clip);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void setup() {
loadClip();
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(false);
}
private void goBlooey(Throwable t) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder
.setTitle("Exception!")
.setMessage(t.toString())
.setPositiveButton("OK", null)
.show();
}
}