android device unable to play music via android studio - java

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();

Related

How to play music using MusicPlayService

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.

Application - voice recorder run once then crashes - how to set up try&catch

I have this application that records the users voice and then play it. My problem is that the app works fine the first cycle, I can record, stop recording and play the sound. When I then click record for the second time the application crashes. I use the permissions "Write external storage" and "Record Audio" in the manifest file. If someone knows what is wrong, please help me out!
package com.example.t.voicerecorder;
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.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.time.LocalTime;
public class MainActivity extends AppCompatActivity {
private Button playBtn;
private Button stopBtn;
private Button startBtn;
private String outputFile;
private MediaRecorder recorder;
MediaPlayer player=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn=findViewById(R.id.ButtonPlay);
startBtn=findViewById(R.id.ButtonStart);
stopBtn=findViewById(R.id.ButtonStop);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
outputFile= Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
recorder.setOutputFile(outputFile);
}
public void StartRecording(View view) {
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException ex) {
} catch (IOException iox) {
}
startBtn.setEnabled(false);
playBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording has started",Toast.LENGTH_LONG).show();
}
public void StopRecording(View view){
recorder.stop();
recorder.release();
recorder=null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
startBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording has stopped", Toast.LENGTH_LONG).show();
}
public void PlayRecording(View view){
player=new MediaPlayer();
try{
player.setDataSource(outputFile);
player.prepare();
player.start();
Toast.makeText(getApplication(), "Playing last recording", Toast.LENGTH_LONG).show();
}
catch (Exception ex){
}
}}

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 :)

Thread start was failing in the Activity

Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start(); //Error -1
Error 1 : Syntax error on token "start", Identifier expected after
this token
The thing is, you shouldn't have your th.start() outside your class methods. You can't put it randomly inside your class like that.
Your th.start(); statement should be present in some method in your Activity class. You can't just have that lying around somewhere in the activity.
In your case, it could go in the OnCreate() method, but the thread creation must be done before you start the thread there.
try this
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar) {
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
Thread th = new Thread(){
public void run()
{
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
};
th.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
ourSong.release();
}
}
This may help u...
in onCreate Method
Thread currentThread = new Thread(this);
currentThread.start();
after on create
public void run() {
try {
Thread.sleep(4000);
threadHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
//don't forget to deal with the Exception !!!!!
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Intent in = new Intent(getApplicationContext(),****.class);
startActivity(in);
}
};
you can also try this :)
package com.askselva.simple;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity{
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle selvaLovesKumar){
// TODO Auto-generated method stub
super.onCreate(selvaLovesKumar);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this, R.raw.airtel);
ourSong.start();
new Thread(new Runnable()){
public void run(){
try{
sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent openMainActivity = new Intent("com.askselva.simple.MENU");
startActivity(openMainActivity);
}
}
}.start();
}
#Override
protected void onPause(){
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
}

Error Playing File: NullPointerException in Android

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();`

Categories