I have a problem where I can't keep the music playing when chaning the screen orientation in my program. I tried adding android:configChanges="keyboardHidden|orientation|screenSize inside the MainActivity in the AndroidManifest.xml file, but although it keeps the music playing, it also disables the different layout for the landscape mode.
Here is the code for the MainActivity:
package com.example.gomoku;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up click listeners for all the buttons.
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View highScoreButton = findViewById(R.id.high_score_button);
highScoreButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_button:
startGame();
break;
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
case R.id.exit_button:
finish();
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, Prefs.class));
return true;
}
return false;
}
#Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.main);
}
#Override
protected void onPause() {
super.onPause();
Music.stop(this);
}
private void startGame() {
Intent intent = new Intent(MainActivity.this, Game.class);
startActivity(intent);
}
}
And here is the code for Music:
package com.example.gomoku;
import android.content.Context;
import android.media.MediaPlayer;
public class Music {
private static MediaPlayer mp = null;
/** Stop old song and start new one. */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences.
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
}
}
/** Stop the music. */
public static void stop(Context context) {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Editing the original code;
package com.example.gomoku;
import android.content.Context;
import android.media.MediaPlayer;
public class Music {
//####First change is here####
//adding a variable to store the time of music being played.
private static int pos = 0;
private static MediaPlayer mp = null;
/** Stop old song and start new one. */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences.
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
//####Second change is here####
//this will continue the music from wherever it was paused
mp.seekTo(pos);
}
}
/** Stop the music. */
public static void stop(Context context) {
if (mp != null) {
//####Third change is here####
mp.pause();//to pause the music
//to store current pause time in pos
//as pos is static it will retain the value
pos = mp.getCurrentPosition();
mp.stop();
mp.release();
mp = null;
}
}
}
add this code to stop the app when back key is pressed.
#Override
public void onBackPressed() {
pos = 0;
super.onBackPressed();
mp.release();
System.exit(0);
}
Now this app will:
Play music in loop when it starts.
Continue the music when screen orientation is changed.
Resume music when app is restarted after pressing home button.
Restart song if the back button was pressed.
Related
I wanna make "Play/Stop" button. When button "Play" is clicked, the song must be played and its text should be converted into "Stop" and when "Stop" is clicked, the button text should be changed into "Play" again and song should start again to play from the beginning.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button btn_playStop;
private MediaPlayer mediaPlayer;
private boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Play Music");
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.zara_sa);
btn_playStop = (Button)findViewById(R.id.btn_play_stop);
btn_playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() && flag==true){
stopSong();
}
else if (flag == false){
playSong();
}
}
});
}
public void playSong(){
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
public void stopSong() {
mediaPlayer.stop();
btn_playStop.setText("Play");
flag = false;
}
}
You must call mediaPlayer.prepare(); if you called mediaPlayer.stop(); so in the first time you can just call mediaPlayer.start(); but in the next times you should call mediaPlayer.prepare(); before mediaPlayer.start();
public void playSong(){
try {
mediaPlayer.prepare();
} catch (IOException e) {
}
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
I would like my button (should it be a button or sth else?) to to play music when I hover on it and stop at HOVER_EXIT. What should I implement for
case MotionEvent.ACTION_HOVER_MOVE: to make button play music still, without pauses from ENTER to EXIT and on MOVE dont do anything?
There is also an error - when I try to open a screen with this hoverbutton, app crashes and turns off.
Here is my java code:
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class DisplayActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
b1 = (Button)findViewById(R.id.button1);
b1.setOnHoverListener(new View.OnHoverListener()
{
#Override
public boolean onHover(View v, MotionEvent event) {
MediaPlayer player=MediaPlayer.create(DisplayActivity.this,R.raw.sound);
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
player.start();
break;
case MotionEvent.ACTION_HOVER_EXIT:
player.stop();
break;
}
return true;
}
});}`
public class DisplayActivity extends AppCompatActivity {
private MediaPlayer player;
#Override
protected void onResume() {
super.onResume();
// create media player only when required
player = MediaPlayer.create(this, R.raw.sound);
// this will keep the audio playing, even if you hover for long time
player.setLooping(true);
}
#Override
protected void onPause() {
super.onPause();
// release is as soon as possible
player.release();
player = null;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
findViewById(R.id.button1).setOnHoverListener(new View.OnHoverListener() {
#Override
public boolean onHover(
View v,
MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
player.start();
break;
case MotionEvent.ACTION_HOVER_EXIT:
// if you choose to stop the player, you need to prepare it again by calling player.prepare(); before restarting it.
// I chose to pause it and seek it back to beginning
player.pause();
player.seekTo(0);
break;
}
return true;
}
});
}
}
Hope this helps :)
package project.kalmas;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
public class one extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
}
public void onclick2(View view)
{
Intent i=new Intent("project.two");
startActivity(i);
}
public void onclick3(View view)
{
MediaPlayer mp= MediaPlayer.create(this,R.raw.one);
if(mp.isPlaying()){
mp.stop();
} else {
mp.start();
}
}
}
When i click button it play sound then again i click button to stop it wont stop and play sound again which results in double sound playing at one time.Please help
You are creating a new MediaPlayer with every click, instead of keeping a reference to the first one. The MediaPlayer that is playing the sound is different than the MediaPlayer that you are calling isPlaying() on. You need to turn the mp variable into a field so you can keep a reference to it.
I imagine something like this would work:
public class one extends Activity {
MediaPlayer mp;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
mp = MediaPlayer.create(this,R.raw.one);
}
public void onclick2(View view)
{
Intent i=new Intent("project.two");
startActivity(i);
}
public void onclick3(View view)
{
if(mp.isPlaying()){
mp.stop();
} else {
mp.start();
}
}
}
I have created two classes. I want to have a button on class 1 (MainActivity) that when it is pressed, it will take me to class 2 (Alphabet). I have tried numerous ways of doing it and I have been unsuccessful. Here is my original code below. Can anyone help me?
Sorry, I am new to app developing.
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The code below is the code that I attempted which includes 'Intent'
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
**View button6 = findViewById(R.id.button6);
button6.setOnClickListener(this);**
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
**case R.id.button6:
Intent i = new Intent(this, Alphabet.class);
startActivity(i);
break;**
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
If you want to do custom coding, you need to learn langauges like Objective-C or Swift to develop iOS app. Or another way is mobile app development platform. With the help of app development tools you can develop apps with drag & Drop facilities without writing a single line of code.
I am an iOS app developer, I have tried most of the mobile app development platforms. I have developed more than 50 apps till today with the help of Phonegap, Telerik, Configure.IT etc. They are running successfully on app store.
As per my experience in this field, I recommend developers as well as beginners to use mobile app development platform like http://www.configure.it/, because it provides automatic coding, app preview facility, direct API connect and a lot more features. These things save a lot more development time and provides fast and well designed app in much less time.
The main benefit of this tool, it is web based platform so you do not require to buy Mac system, you can make an app from any place as well as from any system.
Currently in MainActivity Activity you are not adding setOnClickListener to button6 but in onClick method you are trying to start Activity on button6 click . to get your code working add setOnClickListener to button6 also as
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
Button button6 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(this);
and register Alphabet Activity in Manifest as :
<activity android:name=".Alphabet" />
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
Button button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
case R.id.button6:
Intent i = new Intent(getApplicationContext(), com.example.lullabymain.Alphabet.class);
startActivity(i);
break;
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
When you set the context of {this} you are using the {this} of the onClickListener. use getApplicationContext();
Button button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(getApplicationContext(), Alphabet.class));
}
});
What are the errors that your code is throwing?
What you need to do is set on click listeners on the required buttons
and followed by Intents to go to your new class for example
Intent i5 = new Intent(this, HadithList.class);
startActivity(i5);
i use these lines to play some audio file with mediaplayer, both on a service and in an activity, yet there is no sound on my device, what could be the reason? and what should i try to do to understand whats wrong and finally fix that?
MediaPlayer mp = MediaPlayer.create(this, R.raw.alert);
mp.start();
Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(objectFilePath);
viewMediaIntent.setDataAndType(Uri.fromFile(file), "audio/*");
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);
http://developer.android.com/reference/android/media/MediaPlayer.html
Check out the state diagram in the MediaPlayer docs.
After you've created the MediaPlayer it is in the Idle state. As you can see, you need to initialize and prepare it before you call start().
Check the following code, it works fine for me. I hope it will work for you also.....Dont forget to add Audio PlayBack permission in android Manifest File
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}