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 :)
Related
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.
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();
}
}
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();
I've been working on this for a while, trying to get this tutorial to work (http://united-coders.com/nico-heid/an-android-seekbar-for-your-mediaplayer/), but I haven't had any luck. The audio playback works perfect, but the SeekBar doesn't move.
package com.example.playingaudio;
import java.io.FileInputStream;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
public class MainActivity extends Activity implements Runnable {
private MediaPlayer mediaPlayer;
private SeekBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
progress = (SeekBar) findViewById(R.id.seekBar1);
}
public void playButton(View view) {
try {
playRecording();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void playRecording() throws Exception {
final MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fileStream = new FileInputStream(
"/sdcard/Download/mySong.mp3");
mediaPlayer.setDataSource(fileStream.getFD());
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
run();
}
private void ditchMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mediaPlayer.getDuration();
progress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(currentPosition);
}
}
}
Try changing this line
final MediaPlayer mediaPlayer = new MediaPlayer();
To, this line
mediaPlayer = new MediaPlayer();
The reason is you already have a class variable mediaPlayer declared and why are you declaring the local variable again with the same name.
The reason your bar is not updating is because you aren't giving it a chance to. You have a constant loop on your UI thread that consists mostly of sleep(). You can't do that and expect the UI to update.
If you look at that tutorial more closely, you'll see that they don't call runOnUiThread(). In fact, at the bottom there is a link back to SO, which shows a bit more of the code involved. There's just a new Thread created, and start() is run. Nothing too tricky.
Example:
(call this method after mediaPlayer.start()):
private void createProgressThread() {
progressUpdater = new Runnable() {
#Override
public void run() {
//...
//...
}
};
Thread thread = new Thread(progressUpdater);
thread.start();
}
I want to play an mp3 file in android, but i get this error:
java.lang.NullPointerException at HelloAndroid.playMusic
My code below
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.net.Uri;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
public MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
Log.i(DebugTag, "Info about my app na");
}
public void playMusic () {
try {
Uri fileName = Uri.parse("http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3");
mp= MediaPlayer.create(this, fileName);
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
What will i do to fix this error?
Thanks
UPDATE
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
//import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
private MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
}
public void playMusic () {
try {
String url = "http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3";
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(url);
mp.prepare();
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
After implementing some of the answers, i now get this error: java.io.IOException: Prepare Failed .: status = 0x1
add mp.prepare(); before mp.start();
Your issue is you aren't checking mp before you call methods on it. According to the documentation, if MediaPlayer.create fails, it will return null.
Rule of thumb with NullPointerExceptions: go back and check your returns. Something is usually returning null when you aren't expecting it to, and you try to call a method on it. In this case, you aren't calling anything on fileName, so that's safe. You're calling something on mp, so that's probably what's doing you in.
[edit]
Why the audio isn't playing:
You aren't calling setAudioStreamType(AudioManager.STREAM_MUSIC); and the use of URIs in the creation of a MediaPlayer instance is only for locally stored media. Network media needs to have its location set by calling setDataSource(context, uri);.
From the (very good) documentation:
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();`