How to play music in Thread on Android? - android

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?

Related

How To play radio app in background and show Widget on notification bar?

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.

Android radio streaming, the steam link doesnt play

I've followed up zvzej's post on Online radio streaming app for Android
I am encountering 2 problems:
1st.) The stream link don't play, though buttonPlay.enabled(false) does work, I also don't see the progressbar, eventhough onClick of Play it should be visible. Does this mean the script cant go beyond
playSeekBar.setVisibility(View.VISIBLE);
in startPlaying() ?
2nd.) After clicking Play, then stop, then back to play, the application force crashes, sometimes it requires more clicks, sometimes fewer.
Code:
package com.afghan.radios;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class ArmanFMRadio 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.armanfm);
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);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://usa8-vn.mixstream.net:8138");
} 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.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
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) {
try {
player.prepare();
player.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}

error record and play audio in android

i've been trying to record and play recorded audio in android . I've used MediaRecorder and MediaPlayer class for the same.
My code contain 3 segments:
startrecording()
stoprecording()
playaudio
But there's an error in my code fragement and whenever i execute it ,the startrecording() function implements catch block.
package hare.krishna;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class Recordplay2Activity extends Activity
{
Button play1,record1,stop1;
TextView status1;
MediaRecorder m1=null;
MediaPlayer m2=null;
String path;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play1=(Button)findViewById(R.id.play);
record1=(Button)findViewById(R.id.record);
stop1=(Button)findViewById(R.id.stop);
status1=(TextView)findViewById(R.id.status);
OnClickListener recordListener = new OnClickListener()
{
public void onClick(View v)
{
startrecording();
}
};
OnClickListener stopListener = new OnClickListener()
{
public void onClick(View v)
{
stoprecording();
}
};
OnClickListener playListener = new OnClickListener()
{
public void onClick(View v)
{
playaudio();
}
};
record1.setOnClickListener(recordListener);
stop1.setOnClickListener(stopListener);
play1.setOnClickListener(playListener);
}
public void startrecording()
{
status1.setText("GET READY FOR RECORDING");
try
{
m1=new MediaRecorder();
m1.setAudioSource(MediaRecorder.AudioSource.MIC);
m1.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
m1.setOutputFile(path);
m1.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
m1.prepare();
m1.start();
}
catch(Exception e)
{
status1.setText("ERROR IN startrecording FUNCTION ");
}
}
public void stoprecording()
{
try
{
status1.setText("TIME TO STOP MEDIA");
m1.stop();
m1.reset();
m1.release();
}
catch(Exception e)
{
status1.setText("ERROR IN stoprecording FUNCTION");
}
}
public void playaudio()
{
status1.setText("PLAYING RECORDER AUDIO");
try
{
m2=new MediaPlayer();
m2.setDataSource("/sdcard/output.3gp");
m2.prepare();
m2.start();
}
catch(Exception e)
{
System.out.println("ERROR in playaudio FUNCTION");
}
}
}
I solved it. I changed AudioEncoder from:
m1.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
to:
m1.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT)

Mp3 not playing in Android

I create a simple splash screen which has a sound(mp3)
package in.isuru.Hello;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//splash is a xml layout
setContentView(R.layout.splash);
//haha is a mp3 file.
player = MediaPlayer.create(Splash.this, R.raw.haha);
player.start();
//Timer to pause 5 seconds before go to next intent
Thread timer = new Thread(){
public void run(){
try{
//player starts playing mp3 file
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint = new Intent("in.isuru.HELLO");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
player.release();
finish();
}
}
I tried android MediaPlayer not playing mp3 file
too but it didn't work. I consulted Android Documentation too. but nothing seems to work either.
put player.prepare(); before player.start();
See if that works

Play mp3 file from raw resource on click of a TextView

I want to play a certain mp3 file when a text is clicked. For example, I clicked the word "Nicholas", the app have to play nicholas.mp3.
Sorry for my messy code, I'm new to android dev:
package com.example.playword;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
//import android.os.Handler;
import android.view.View;
//import android.view.View.OnClickListener;
//import android.widget.Button;
import android.widget.TextView;
public class PlayWord extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//final Handler mHandler = new Handler();
final TextView nicholas = (TextView) findViewById(R.id.nicholas);
final TextView was = (TextView) findViewById(R.id.was);
nicholas.setText("Nicholas ");
was.setText("was ");
/*
Button btn = (Button) (findViewById(R.id.nicholasBtn));
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
nicholas.setText("Nicholas (Clicked!) ");
}
});
*/
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.nicholas: // doStuff
MediaPlayer mPlayer = MediaPlayer.create(null, R.raw.aaanicholas);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
nicholas.setText("Nicholas (Clicked!) ");
break;
case R.id.was: // doStuff
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.aaawas);
try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer1.start();
was.setText("was (Clicked!) ");
break;
}
}
};
findViewById(R.id.nicholas).setOnClickListener(handler);
findViewById(R.id.was).setOnClickListener(handler);
}
}
When I run this, I'm getting a force close error. Do you have a much better idea on this?
You need to pass in a context instance into MediaPlayer.create method:
MediaPlayer mPlayer = MediaPlayer.create(PlayWorld.this, R.raw.aaanicholas);
Also, after the create() call, prepare is already executed, so you don't need to execute it explicitly, just invoke start() right after create().
When you create the mPlayer object you should pass it the Context, which is in your case PlayWord.this.
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
mPlayer.start();
val mediaPlayer = MediaPlayer.create(this,R.raw.music)
mediaPlayer.isLooping=true
mediaPlayer.start()
music_on_off_button.setOnClickListener {
if (mediaPlayer.isPlaying){
mediaPlayer.pause()
}else{
mediaPlayer.start()
}
}
You can detect weather the music is playing or not by using isPlaying() method

Categories

Resources