-1

First of all, I followed this tutorial to make the music player app. http://www.java2s.com/Code/Android/Media/UsingServicetoplaymediafile.htm

The app works fine. Later I modified the code to send a link from MainActivity to Service so that the MediaPlayer in the Service can stream the audio from the link. Now the app is not working. When I click "Start Playback" button the app crashes. I added internet permission in Manifest file. Below is my code.

MainActivity.java

package com.example.musicplayer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {

      Button startPlaybackButton, stopPlaybackButton;
      Intent playbackServiceIntent;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
        stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);

        startPlaybackButton.setOnClickListener(this);
        stopPlaybackButton.setOnClickListener(this);

        playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
      }

      public void onClick(View v) {
        if (v == startPlaybackButton) {

          playbackServiceIntent.putExtra("song_link", "http://a2z3gp.com/Telugump3%20Songs/Telugump3/A%20TO%20Z%20TELUGU%20HQ%20MP3%20SONGS/E/Eduruleni%20Manishi/Are_Eelakotti.mp3" );
          startService(playbackServiceIntent);

        } else if (v == stopPlaybackButton) {

          stopService(playbackServiceIntent);

        }
      }
    }

BackgroundAudioService.java

package com.example.musicplayer;
import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.IBinder;

public class BackgroundAudioService extends Service implements OnCompletionListener {
  MediaPlayer mediaPlayer;
  String data;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) { 

      data=(String) intent.getExtras().get("song_link");
      try {
        mediaPlayer.setDataSource(data);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
    }
    return START_STICKY;
  }

  public void onDestroy() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    mediaPlayer.release();
  }

  public void onCompletion(MediaPlayer _mediaPlayer) {
    stopSelf();
  }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Background Audio Player"
        />
   <Button android:text="Start Playback" android:id="@+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
   <Button android:text="Stop Playback" android:id="@+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Shahid Roshan
  • 105
  • 3
  • 14
  • In order to pass data from activity to service you need to bind your activity with your service . Refer this http://developer.android.com/guide/components/bound-services.html – Preethi Rao Apr 01 '15 at 09:53
  • create raw folder and add song in raw folder than give the raw folder path –  Apr 01 '15 at 09:55
  • But I want to stream audio file from internet @JATIN DEVANI – Shahid Roshan Apr 01 '15 at 10:03
  • http://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778 http://stackoverflow.com/questions/14151661/mediaplayer-service-android – Amrut Bidri Apr 01 '15 at 10:07
  • Or else you can use SharedPreferences. I dont prefer it, but if you want to use it,You can. –  Apr 01 '15 at 10:12

3 Answers3

0

First of all your MediaPlayer is not initialized hence the crash.

here try this:

   package com.example.musicplayer;
    import java.io.IOException;

    import android.app.Service;
    import android.content.Intent;
    import android.media.AudioManager;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnCompletionListener;
    import android.os.Bundle;
    import android.os.IBinder;

    public class BackgroundAudioService extends Service implements OnCompletionListener {
      MediaPlayer mediaPlayer;
      String data;

      @Override
      public IBinder onBind(Intent intent) {
        return null;
      }

      @Override
      public void onCreate() {

      }
private void initMedia(String data) {
        mediaPlayer= MediaPlayer.create(BackgroundAudioService.this, Uri.parse(data));
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(this);
    }



      @Override
      public int onStartCommand(Intent intent, int flags, int startId) { 
     if (intent == null || intent.getExtras() == null) // because this will             //start also first time you run the service even with no extras
        return;

          data=(String) intent.getExtras().get("song_link");
          if(mediaPlayer ==null)
            initMedia(data);
        else {
            mediaPlayer.setDataSource(data);
        }
        if (!mediaPlayer.isPlaying()) {
          mediaPlayer.start();
        }
        return START_STICKY;
      }

      public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.stop();
        }
        mediaPlayer.release();
      }

      public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
      }

    }

PS didnt try it but it is just a guide ;)

murielK
  • 1,000
  • 1
  • 10
  • 21
0

Please replace code

@Override
  public void onCreate() {

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
  }

To

@Override
    public void onCreate()
    {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(this);
    }

And add below line before mediaPlayer.start(); line in Service.

mediaPlayer.prepare();
0

cause your're using an online source, you need to buffering
also you should call mediaPlayer.prepareAsync() before start,mediaPlayer.prepare()might take long
same problem here: https://stackoverflow.com/a/15776134/3487232

Community
  • 1
  • 1
Amir
  • 1,250
  • 18
  • 22