Good day! As usual - I am starting to learn Android programming and have faced unexpected difficulty while trying to create basic MediaPlayer app. Audio file is stored in res/raw. It is accessed with create(). I have read a few manuals on how to build a media player app and was convinced that using prepare() and prepareAsync() was not necessary in case if file is stored in res/raw folder. So here is my initial code
private MediaPlayer playerM = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMusic(R.raw.sleep_away);
}
});
Button stopButton = (Button) findViewById(R.id.pauseButton);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopMusic();
}
});
}
private void playMusic(int rid) {
playerM.create(this, rid);
playerM.start();
}
private void stopMusic() {
playerM.stop();
}
}
Since that I have made numerous changes, but nothing helped. According to dev.android manual on MediaPlayer the code above should work. However it results in the following errors:
E/MediaPlayer: start called in state 1, mPlayer(0x0)
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)
Probably I am just making some blunt mistake. Any help would be much appreciated.
Solved by myself
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Uri myUri = Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.sleep_away);
System.out.println(myUri);
playerM.setDataSource(v.getContext(), myUri);
playerM.prepare();
playerM.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer playerM){
playerM.start();
}
});
}catch(IOException e){
e.printStackTrace();
}
}
});
I know I should add other methods to change State, but the main purpose was to get it to play file.
Related
In Android studios i made Soundboard in which i have 4 activities when i'm on first activity i can press sounds all day and they play but right after i click next for second activity when i try to play them they won't play sound. I can click like 7 times and they stop.
I look everywhere but nothing works i even changed whole code again still same thing happens.
Button button1;
Button theuniverserequired, iusedthestones, etc more sounds....
iaminevitable = (Button) findViewById(R.id.iaminevitable);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.iaminevitable);
iaminevitable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
iusedthestones = (Button) findViewById(R.id.iusedthestones);
final MediaPlayer mp2 = MediaPlayer.create(this,
R.raw.iusedthestones);
iusedthestones.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp2.start();
}
}); etc....
button1 = findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent int1 = new Intent(MainActivity.this, Activity2.class);
startActivity(int1);
}
});
there is nothing in error messages for why is this happening
First off: Declare your MPs outside your onCreate to prevent it from garbage collected when activity is paused
private MediaPlayer mp,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = new MediaPlayer.create(...
mp2 = new MediaPlayer.create(...
Further more: Drop off resources used by MPs when activity stops to avoid memory leaks which may force your app to crash on continuous usage.
#Override
protected void onStop() {
super.onStop();
if (mp != null) {
mp.reset();
mp.release();
mp = null;
}
if (mp2 != null) {
mp2.reset();
mp2.release();
mp2 = null;
}
}
The code I have so far is:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SoundPlayer(View view) {
MediaPlayer soundMediaPlayer1 = MediaPlayer.create(this, R.raw.gun_sound);
soundMediaPlayer1.start();
}
public void DogSound(View view) {
MediaPlayer soundMediaPlayer2 = MediaPlayer.create(this, R.raw.cat_sound);
soundMediaPlayer2.start();
}
public void NewSound(View view) {
MediaPlayer soundMediaPlayer3 = MediaPlayer.create(this, R.raw.new_sound);
soundMediaPlayer3.start();
}
public void LaughTrack(View view) {
MediaPlayer soundMediaPlayer12 = MediaPlayer.create(this, R.raw.laugh_sound);
soundMediaPlayer12.start();
}
public void HorseSound(View view) {
MediaPlayer soundMediaPlayer4 = MediaPlayer.create(this, R.raw.horse_sound);
soundMediaPlayer4.start();
}
public void HeySound(View view) {
MediaPlayer soundMediaPlayer5 = MediaPlayer.create(this, R.raw.hey_sound);
soundMediaPlayer5.start();
}
private void Stop() {
startActivity(new Intent(this, MainActivity.class));
}
public void stop(View view) {
Stop();
}
}
The problem I face is that all the sounds overlaps and plays. I have a STOP button set up, but have no idea has to how to make it stops the media. Any feedback is helpful.
Thank you.
First of all, I would use only one Instance of the MediaPlayer. You can then use mediaPlayer.stop() to stop a sound and prepare the next one.
See the state diagram on https://developer.android.com/reference/android/media/MediaPlayer.html
1) Make the object of MediaPlayer in onCreate method don't create in every new method.
2) Before playing the music in another method first use stop() function to stop current playing sound(like mediaPlayer.stop(); ) then play the sound by start().
I am making an app where bgm start from main page. But I couldn't find a way to turn it off when starts learning.
Can I remotely switch off bgm from different java file
This is my 1st java,mainmenu.class
public class mainmenu extends AppCompatActivity {
MediaPlayer bkgrdmsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button btn = (Button) findViewById(R.id.mula);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_belajar_latihan = new Intent(getApplicationContext(), taqi.mengaji.belajar_latihan.class);
startActivity(ke_belajar_latihan);
}
});
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
bkgrdmsc.start();
}
}
This is the other file I want to remotely off the bgm when starting the learning session(as student start to learn)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.belajar_hija_baris);
Button btn=(Button) findViewById(R.id.hijaiyyah);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_hijaiyah=new Intent(getApplicationContext(),taqi.mengaji.hijaiyyah.class);
startActivity(ke_hijaiyah);
}
});
}
I want R.id.hijaiyyah to navigate to learn xml also stop bgm
Please help I'm a newbie XD
Make an singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 2 activities for eg:
public class MusicManager {
private static MusicManager refrence = null;
public static MusicManager getInstance(){
if(refrence == null){
refrence = new MusicManager ();
}
return refrence;
}
}
Add a public method to this singleton class to start and stop music
public void initalizeMediaPlayer(Context context, int musicId){
// add initalization of media player in it and loop it
MediaPlayer bkgrdmsc;
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
}
public void startPlaying(){
bkgrdmsc.start();
}
public void stopPlaying(){
bkgrdmsc.stop();
}
//Add stuff like pausing and resuming if you desire
To use this class add this to any activity you want to play music:
MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
MusicManager.getInstance().startPlaying();// to start playing music
MusicManager.getInstance().stopPlaying(); // to stop playing music
You can also use service to perform this task as service runs in background. You can start and stop service any time in your code.
I am trying to implement play/pause in a single button however when i try to press it again it just stars the song again overlapping the sound playing. i have search ways and tried this method and it seems it is not working for me. thank you
private OnClickListener handler1 = new OnClickListener(){
public void onClick(View v){
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
if (mpE.isPlaying()) {
mpE.pause();
} else {
mpE.start();
}
}
};"
You are creating the the media player every time. Instead try moving
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
to outside of the handler.
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
I just updated my app on the play store and i started receiving crash reports from people, one was a person i know, so he started helping me to solve this problem, and i discovered that the problem is caused by something i didn't even modify.
The code looks like this
The part that's causing the problem is the bulb.onClickListener
public class Bulb extends Activity {
public boolean isAwake = false;
boolean timerActivated = false;
static ImageView glow;
public static boolean bulbActIsRunning = false;
public void startWake() {
Intent wS=new Intent(getBaseContext(), WakeService.class);
startService(wS);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton bulb = (ImageButton) findViewById(R.id.bulb);
ImageButton ghl = (ImageButton) findViewById(R.id.ghl);
glow = (ImageView) findViewById(R.id.glow);
if (WakeService.isAwake) {
glow.setVisibility(View.VISIBLE);
}
else {
glow.setVisibility(View.INVISIBLE);
}
bulb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startWake();
if (WakeService.isAwake) {
glow.setVisibility(View.INVISIBLE);
}
else {
glow.setVisibility(View.VISIBLE);
}
}
});
ghl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geekshavelanded.com/"));
startActivity(browserIntent);
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
glow = (ImageView) findViewById(R.id.glow);
if (WakeService.isAwake) {
glow.setVisibility(View.VISIBLE);
}
else {
glow.setVisibility(View.INVISIBLE);
}
}
#Override
public void onStart() {
super.onStart();
bulbActIsRunning = true;
}
#Override
public void onStop() {
super.onStop();
bulbActIsRunning = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
After my friends clicks the bulb button the app crashes without reason, i've put some toast notification at the beginning of the onClickListener to see if it appeared before crashing, but it didn't
The crash reports look like this
java.lang.RuntimeException: Unable to start service com.doublep.wakey.WakeService#41740bb8 with Intent { cmp=com.doublep.wakey/.WakeService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2933)
at android.app.ActivityThread.access$1900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1438)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5454)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1436)
at android.os.Parcel.readException(Parcel.java:1384)
at com.android.internal.appwidget.IAppWidgetService$Stub$Proxy.updateAppWidgetIds(IAppWidgetService.java:513)
at android.appwidget.AppWidgetManager.updateAppWidget(AppWidgetManager.java:333)
at android.appwidget.AppWidgetManager.updateAppWidget(AppWidgetManager.java:400)
at com.doublep.wakey.WakeService.keepAwake(WakeService.java:86)
at com.doublep.wakey.WakeService.onStartCommand(WakeService.java:48)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2912)
... 10 more
Can anyone see something suspicious?
I didn't even touch the code of this activity when i was updating my app, and everything else works fine, because i can call the service from a widget aswell.
So the problem must be here
I also modified the min SDK from 8 to 7 (but to see if it works i've put it back to 8)
And i compressed some graphics a little bit more to save space
EDIT oh i forgot to say, this happens only to few devices, on most it seems working fine
UPDATE 2 this is the piece of code that caused those issues
AppWidgetManager mgr=AppWidgetManager.getInstance(this);
mgr.updateAppWidget(ToggleWidget.appWidgetId, ToggleWidget.remoteViews);
Please check the parameter to updateAppWidget(). Ether remote view is null or you are setting null bitmap.