How to play music using MusicPlayService - java

I'm a student and just started learning java and android(currently using android studio). I have been following a tutorial with video streaming and music streaming. but I'm currently following with music streaming.
Code is fine but the problem is It won't stream the music. Also there's no error showing that I missed something or anything in the program. It is running on the emulator but it just wont play the music.
Below is my code for the MainActivity.java:
package com.name.package.yb;
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
private Button btnPlayStop;
private boolean boolMusicPlaying = false;
Intent myService;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
myService = new Intent(MainActivity.this, MusicPlayService.class);
initViews();
setListeners();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void initViews() {
btnPlayStop = (Button) findViewById(R.id.myButton);
btnPlayStop.setText("Stream Music");
}
private void setListeners() {
btnPlayStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnPlayStopClick();
}
});
}
private void btnPlayStopClick() {
if (!boolMusicPlaying) {
btnPlayStop.setText("Pause Streaming");
playAudio();
boolMusicPlaying = true;
} else {
if(boolMusicPlaying){
btnPlayStop.setText("Play Stream");
stopPlayService();
boolMusicPlaying = false;
}
}
}
private void stopPlayService() {
try {
stopService(myService);
} catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
boolMusicPlaying = false;
}
private void playAudio() {
try {
startService(myService);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
And My Service named MusicPlayService.java (I want to play the music in background like the music player on phone):
package com.name.package.yb;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;
public class MusicPlayService extends Service {
private MediaPlayer mediaPlayer = new MediaPlayer();
private static final String AUDIO_STRING = "http://musicsite.streammusic.com/file";
#Override
public void onCreate(){
super.onCreate();
//mediaPlayer.setOnCompletionListener(this);
//mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setVolume(100,100);
//mediaPlayer.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(AUDIO_STRING);
// Prepare mediaplayer
mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
public IBinder onBind(Intent arg0) {
return null;
}
public IBinder onUnBind(Intent arg0) {
return null;
}
}
P.S apk was succefully installed in the emulator and button is clickable. It just wont' play the music.

Your code seems fine, perhaps do you add service to your Manifest?
<service android:enabled="true" android:name=".MusicPlayService" />
[
Welcome to programming in Android, the best way to debug Android Code is by adding logs to your codes. You can use Log.d, Log.e etc to print the value of the variable pass by methods.
]

try this out:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

you can try
mediaPlayer.setDataSource(AUDIO_STRING);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
You also need to permission for INTERNET if you play music online or READ_EXTERNAL_STORAGE if you play music from memory.

Related

Media Player Notification In Android

I have created an android app which has the activity of a music player which I have created but I want that when there is music play then there is a notification show of a media player which has pause / stop and an image show.
Like This:-
But I do not know how to do it! Please Someone Help Me😢
My Codes:-
player_ui.java
package com.musicwala.djaman;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.Button;
import android.media.MediaPlayer;
import android.net.Uri;
import java.io.IOException;
import android.widget.SearchView.OnCloseListener;
import java.util.Timer;
import java.util.TimerTask;
import android.media.PlaybackParams;
import android.graphics.PorterDuff;
import android.view.View;
import android.support.v4.app.NotificationCompat;
import android.content.ContentResolver;
import android.app.NotificationManager;
import android.content.Context;
//import wseemann.media.FFmpegMediaMetadataRetriever;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.Image;
import android.widget.ImageView;
public class play_ui extends Activity
{
static MediaPlayer mp;
TextView songtext;
String path;
SeekBar sb;
Button pause;
Button previous;
Button next;
Thread updateSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO: Implement this method
super.onCreate(savedInstanceState);
setContentView(R.layout.music_player_ui);
songtext = (TextView) findViewById(R.id.txtSongLabel);
songtext.setSelected(true);
String name = getIntent().getStringExtra("file");
path = (String) getIntent().getStringExtra("path");
songtext.setText(name);
pause = (Button) findViewById(R.id.pause);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
//final SeekBar seekbar = (SeekBar) findViewById(R.id.seekBar);
sb=(SeekBar)findViewById(R.id.seekBar);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(path);
rawArt = mmr.getEmbeddedPicture();
final ImageView image = (ImageView) findViewById(R.id.album_art);
// if rawArt is null then no cover art is embedded in the file or is not
// recognized as such.
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
image.setImageBitmap(art);
// Code that uses the cover art retrieved below.
/* updateSeekBar=new Thread(){
#Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
while(currentPosition < totalDuration){
try{
sleep(500);
currentPosition=mp.getCurrentPosition();
sb.setProgress(currentPosition);
}
catch (InterruptedException e){
}
}
}
};*/
updateSeekBar = new Thread() {
#Override
public void run() {
int runtime = mp.getDuration();
int currentPosition = 0;
int adv = 0;
while ((adv = ((adv = runtime - currentPosition) < 500)?adv:500) > 2) {
try {
currentPosition = mp.getCurrentPosition();
if (sb != null) {
sb.setProgress(currentPosition);
}
sleep(adv);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
sb.setProgress(runtime);
break;
}
}
}
};
if(mp != null){
mp.stop();
mp.release();
}
//int pos = 0;
mp = new MediaPlayer();
try
{
mp.setDataSource(path);
mp.prepare();
//sb=(SeekBar)findViewById(R.id.seekBar);
//sb.setMax(mp.getDuration());
}
catch (IOException e)
{}
catch (IllegalArgumentException e)
{}
catch (SecurityException e)
{}
catch (IllegalStateException e)
{}
mp.start();
//Find the seek bar by Id (which you have to create in layout)
// Set seekBar max with length of audio
// You need a Timer variable to set progress with position of audio
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
sb.getThumb().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
sb.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i,
boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sb.setMax(mp.getDuration());
if(mp.isPlaying()){
pause.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
mp.pause();
}
else {
pause.setBackgroundResource(R.drawable.pause);
mp.start();
}
}
});
}
}

Trying to get the MediaRecorder to reset and also to continue running when I change to a different class

Currently I am facing three issues:
Getting the MediaRecorder to reset instead of release.
I think i need to create a new instance of the MediaRecorder and release() it as well, but I do not know where.
I want it to keep recording audio until the phone dies and even when the user changes to a different screen (i.e. going to a new class).
I have tried to google this but do not know how to achieve it.
Edit - I figured out how to use SimpleDateFormat!
Edit 2 - Realised I need to create a started service for my 2nd issue.
My code is as follows
Class:
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Drugs extends AppCompatActivity {
WebView myBrowser;
MediaRecorder mRecorder;
private static String audioFilePath;
public boolean isRecording = false;
MediaPlayer mediaPlayer;
public boolean isPlaying = false;
SimpleDateFormat simpledate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drugs);
myBrowser = (WebView) findViewById(R.id.mybrowser);
myBrowser.loadUrl("file:///android_asset/drugs.html");
myBrowser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
Button btndrugslaw = (Button) findViewById(R.id.drugslaw);
btndrugslaw.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intentdruglaw = new Intent(Drugs.this, DrugLaw.class);
startActivity(intentdruglaw);
}
});}
public void RecordButton (View view) {
if(mRecorder == null){
audioFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + simpledate
+ "/myaudio.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(audioFilePath);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if (isRecording) {
try{
stopRecording();
isRecording = false;
((Button)view).setText("Start Recording");
}catch(Exception e){
e.printStackTrace();
}
} else {
try{
startRecording();
isRecording = true;
((Button)view).setText("Stop Recording");
}catch(Exception e){
e.printStackTrace();
}
}
}
public void startRecording() throws IllegalStateException, IOException{
mRecorder.prepare();
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.start();
}
public void stopRecording() throws IllegalStateException, IOException{
mRecorder.stop();
mRecorder.reset();
}
public void StartPlaying(View view) throws IllegalStateException, IOException {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(audioFilePath);
}
if (isPlaying) {
try {
stopPlaying();
isPlaying = false;
((Button)view).setText("Play Audio");
} catch (Exception e) {
e.printStackTrace();
}
} else {
try{
startPlaying();
isPlaying = true;
((Button)view).setText("Stop Audio");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void startPlaying() throws IllegalStateException, IOException {
mediaPlayer.prepare();
mediaPlayer.start();
}
public void stopPlaying () throws IllegalStateException, IOException {
mediaPlayer.release();
}
}

android device unable to play music via android studio

package com.example.darshanms.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import static com.example.darshanms.myapplication.R.raw.splashsound;
public class splash extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle TravisloveBacon){
super.onCreate(TravisloveBacon);
setContentView(R.layout.splash);
mp=MediaPlayer.create(splash.this, R.raw.splashsound);
mp.reset();
mp.start();
Thread timer=new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openMainActivity=new Intent("com.example.darshanms.MAINACTIVITY");
startActivity(openMainActivity);
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
mp.release();
finish();
}
}
I try this to play music in small application. My android device can produce output but cannot play music.
Try switching this lines:
mp=MediaPlayer.create(splash.this, R.raw.splashsound);
mp.reset();
mp.start();
with:
mp=MediaPlayer.create(this, R.raw.splashsound);
mp.prepare();
mp.start();

android when url audio streaming, music didn't stop

Codes in below. when i add mediaplayer.stop();, media player hasn't stop. same thing for mediaplayer.pause(); if works. because icon is changing. But music hasn't stop. And i can't do debuging in android studio. Thanksi in advance.
package ceyhun.musicpuzzle.com;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
Button PlayPause;
private boolean boolMusicPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Baslamak();
}
private void Baslamak() {
PlayPause = (Button)findViewById(R.id.PlayPause);
PlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oynatim();
}
});
}
private void oynatim() {
final MediaPlayer mediaPlayer = new MediaPlayer();
if (!boolMusicPlaying) {
boolMusicPlaying = true;
PlayPause.setBackgroundResource(R.drawable.ic_action_pause);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getString(R.string.rihanna));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Baslamak();
}
else {
mediaPlayer.stop();
//there is a problem. music hasn't stop.
mediaPlayer.reset();
PlayPause.setBackgroundResource(R.drawable.ic_action_play);
boolMusicPlaying = false;
Baslamak();
}
}
}
Each time you run the "oynatim" method, you're instantiating a new class.
final MediaPlayer mediaPlayer = new MediaPlayer();
The line above should only be run once and not every time the method is run. I ran into the same problem when using Android Studio.
On a side note, you have to call mediaPlayer.prepare() or mediaPlayer.prepareAsync() if you want to get mediaPlayer out of a "stopped" states. This happens when you call mediaPlayer.stop().
Edit: Put the final MediaPlayer in the class and not the methods.
private void stopPlaying {
if ( mediaPlayer != null ) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
mediaPlayer is the instance of MediaPlayer in android that you first assign your URL and start play music :)

Android/Java: How to reference from a class to the MainActivity.java

Sorry for the question, probably it is answered within a few minutes.
I'm new to Android App development and have been searching for an answer for about 2 hours, but I don't find a solution.
So, this is my problem:
I created a MainActivity with a very simple layout, only one ToggleButton to start/stop some sound. I got it working with calling the MediaPlayer from within the MainActivity-Class.
Now I want to put the MediaPlayer-Handling into a separate class, such that it can be called from a widget as well.
When rising a Toast or calling a MediaPlayer-Method, I need to refer to the MainActivity, which was (in the MainActivity itself) "this".
But I don't know how to refer to the instance of the MainActivity.
The code is as follows:
package com.heavyloadreverse;
//import java.io.IOException;
import android.app.Activity;
//import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
//import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
//private MediaPlayer mp;
private Sound snd;
private ToggleButton btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (ToggleButton) findViewById(R.id.btn_OnOff);
snd = new Sound();
snd.mp_create(MainActivity.this);
}
public void onToggleClicked(View v) {
// Perform action on clicks
if (((ToggleButton) v).isChecked()) {
snd.mp_start();
} else {
snd.mp_stop();
}
}
/*********************************************************************************
public void mp_create() {
mp = MediaPlayer.create(this, R.raw.truckreverse);
}
public void mp_start () {
Toast.makeText(this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
mp.setLooping(true);
mp.start();
}
public void mp_stop () {
Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
// stop the sound
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mp_init() {
btn.setChecked(false);
}
**********************************************************************************/
public void btn_init() {
btn.setChecked(false);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onRestart() {
super.onRestart();
btn_init();
}
#Override
public void onResume() {
super.onResume();
btn_init();
}
#Override
public void onPause() {
super.onPause();
snd.mp_stop();
}
#Override
public void onStop() {
super.onStop();
snd.mp_stop();
}
#Override
public void onDestroy() {
super.onDestroy();
snd.mp_stop();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
}
The class for the MediaPlayer-Handling:
package com.heavyloadreverse;
import java.io.IOException;
import android.app.Application;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.heavyloadreverse.R;
public class Sound extends Application {
private MediaPlayer mp;
public void mp_create (MainActivity main) {
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
mp = new MediaPlayer();
try {
mp = MediaPlayer.create(this, R.raw.truckreverse);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_start () {
Toast.makeText(MainActivity.this, R.string.start, Toast.LENGTH_SHORT).show();
// start the sound
try {
mp.setLooping(true);
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void mp_stop () {
//Toast.makeText(this, R.string.stop, Toast.LENGTH_SHORT).show();
try {
// stop the sound
mp.stop();
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
--> raises a runtime-error when executing:
--> 03-12 20:23:18.412: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heavyloadreverse/com.heavyloadreverse.MainActivity}: java.lang.NullPointerException
Toast.makeText(main.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> *Multiple markers at this line
- main cannot be resolved to a type
- Line breakpoint:Sound [line: 15] -
mp_create(MainActivity)*
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
--> error in code:
--> No enclosing instance of the type MainActivity is accessible in scope
What do I have to do in order to make the Toast- and MediaPlayer-Calls in "Sound.java" working?
Thanks a lot in advance.
Sven
Option 1
Add 'Context' as a parameter on 'Sound'
public class Sound{
private Context mContext;
Sound(Context context){
mContext = context;
}
...
Toast.makeText(mContext, text, length).show();
...
}
When you create Sound from activity you will do it like new Sound(this);
Option 2
Define an interface in Sound to provide callbacks
public class Sound {
interface OnSoundListener{
public void onSoundStarted();
public void onSoundStopped();
}
}
And your main activity will look like
public class MainActivity implements Sound.OnSoundListener{
#Override
public void onSoundStarted(){
//your toast here
}
}
Personally I prefer the second one, that way you can separate logic from UI.
Not sure if this work, only an idea.
Firs of all extend your Sound class from your MainActivity
public class Sound extends MainActivity {
second, this is the code I use for Toast to work:
Toast.makeText(MainActivity.this,"Your Text Here",Toast.LENGTH_LONG).show();
For Toast this is what you need to do:
Toast toast=Toast.makeText(this, "Hello toast", 2000);
toast.show();
Check this tutorial tutorial if it helps.

Categories