how to play same music file over and over again in android - android

My Android app has a music file that I want it playing when the Main Activity is started and I want the music file to restart when it finishes. So, basically I want it to loop over and over until the user has moved to a different activity.
Below is the class that starts the music file, but when the music is over, it does not restart ...
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainMenu extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
MediaPlayer mPlayer = MediaPlayer.create(MainMenu.this, R.raw.mmt_menu);
mPlayer.start();
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(!manager.isMusicActive())
{
mPlayer.start();
}
}
}
What do I need to do so that when the music stops it restarts again?
Thanks very much!

Call the function:
MediaPlayer.setLooping(true|false)
on the mediaplayerObject after you called MediaPlayer.prepare()
Example:
Uri mediaUri = createUri(context, R.raw.media); // Audiofile in raw
folder Mediaplayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(context, mediaUri);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();

Related

Timer with individual Sound in Foreground

Hello I would like to develop an app in Android that displays
a countdown and plays an individual sound when it expires. The
app has to be in the foreground the whole time.
Problems are still the sound and the app in the foreground.
Unfortunately I have no idea, as I have only recently started
developing with Android.
Thanks for the help!
I have used this template and integrated a method loadMusic, how can I now pause this instead of stop and play music individually?
private void loadMusic() {
if (timerStatus == TimerStatus.PAUSED)
new Runnable() {
#Override
public void run() {
playSound(R.raw.sound1);
}
public void playSound(int sound1) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), (R.raw.sound2));
mp.start();
}
}.run();
}
My Sound class:
package de.codeyourapp.countdowntimer;
import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
public class Sound extends AppCompatActivity {
ImageView imageButton1, imageButton2, imageButton3, imageButton4;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sound);
imageButton1 = findViewById(R.id.iv_bowl1);
imageButton2 = findViewById(R.id.iv_bowl2);
imageButton3 = findViewById(R.id.iv_bowl3);
imageButton4 = findViewById(R.id.iv_bowl5);
MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.sound1);
MediaPlayer mediaPlayer2 = MediaPlayer.create(this, R.raw.sound2);
MediaPlayer mediaPlayer3 = MediaPlayer.create(this, R.raw.sound3);
MediaPlayer mediaPlayer4 = MediaPlayer.create(this, R.raw.sound5);
imageButton1.setOnClickListener(v -> mediaPlayer1.start());
imageButton2.setOnClickListener(v -> mediaPlayer2.start());
imageButton3.setOnClickListener(v -> mediaPlayer3.start());
imageButton4.setOnClickListener(v -> mediaPlayer4.start());
}
}
You can use CountDownTimer of android. You can check this post for help.
Destroy the timer in onPause() to ensure that the timer doesn't work on background.
As to sound - you can add a sound file in your asset folder and take help from this thread to learn how to play the sound.

how to set seekbar progress set to zero if video is finished in android

i am new to android i want to develop application of video player in this video player i need to integrate seekbar. i was stuck in this scenario. the scenario is the seekbar seeking up to video length,at the end of the video(video is finished to play ) seekbar set to zero plz help me how can i implement this scenario.
i do not know how to implement
1)how to set seekbar seeking up to video length/duration
2)if video is fully played how to set seekbar in start position/initial position(before seeking video position)
3)how can i get video is fully played
please any one help me as soon as possible
i found these links may be they help you:
How to play a video using videoview controlled by a seekBar or Progress bar?
How to use a Seekbar in android as a seekBar as well as a progressBar simultaneously?
How can i change the position of a progressBar, after the duration of a videoView?
package com.coderzheaven.pack;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoViewDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showVideo();
}
private void showVideo()
{
VideoView vd = (VideoView)findViewById(R.id.videoview);
Uri uri = Uri.parse("android.resource://"+ getApplication().getPackageName() +"/"+R.raw.asal);
MediaController mc = new MediaController(this);
vd.setMediaController(mc);
vd.setVideoURI(uri);
vd.start();
vd.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//you can set seekbar position here with help of vd.seekTo(progress);
Toast.makeText(getApplicationContext(), "Video completed", Toast.LENGTH_LONG).show();
}
});
}
}
1)how to set seekbar seeking up to video length/duration
you can acheive this by using this code:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
long duration = videoView.getDuration();
}
});
if this works mark this as answer for others help

How to pause a music player programmatically

I have used MUSIC_PLAYER in my application by starting like this:
Intent myint = new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(myint);
And I want to pause this player. How do I do that?
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread mtr = new Thread(){
public void run()
{
try {
Intent myint = new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(myint);
sleep(50000);
// Here I want to pause my application after those 50 seconds.
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent myint = new Intent("nextscreen");
startActivity(myint);
}
}
};
mtr.start();
}
}
In Samsung devices, you can control the music player with these intents:
ICS:
"com.android.music.musicservicecommand.play"
"com.android.music.musicservicecommand.pause"
"com.android.music.musicservicecommand.next"
...
JB:
"com.sec.android.app.music.musicservicecommand.play"
"com.sec.android.app.music.musicservicecommand.pause"
"com.sec.android.app.music.musicservicecommand.next"
...
context.sendBroadcast(new Intent("com.sec.android.app.music.musicservicecommand.pause"));
Another solution is requestAudioFocus in AudioManager (do not forget to release it with abandonAudioFocus). For example:
...
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
...
...
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(listener);
...
You can't do that. Pausing the music player is an internal action inside the application available to the user exclusively, so it cannot be accessed/called from outside of the application.
You can, however, mute the music audio stream using the AudioManager class by calling setStreamMute(AudioManager.STREAM_MUSIC, true).
Code sample:
AudioManager am = (AudioManager)MainActivity.this.getSystemService(Context.AUDIO_SERVICE);
am.setStreamMute(AudioManager.STREAM_MUSIC, true);
See answer here, you can send broadcast to pause or stop the default music player very easy.

Android Mediaplayer Play/Stop help needed

I am trying to create my first android application and what I'm trying to accomplish here is to play a sound and then stop it via the same button.
It kind of works as it plays the sound when I click it and stops when I click it again but will not play when I click it the third time to start the sound again.
I'm eventually going to have a few sounds in here and so would like to know if how my project is laid out correctly? Can I save some time anywhere? Have I got something the wrong way round?
package test.soundy.com;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity {
private MediaPlayer sound;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sound = MediaPlayer.create(Test.this, R.raw.sound1);
Button test = (Button)this.findViewById(R.id.button1);
test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (sound.isPlaying()) {
sound.stop();
} else {
sound.start();
}
}
});
}
}
Any help would be much appreciated, thanks.
WHEN START/PAUSE:
if(sound.isPlaying()){
sound.pause();
}else{
sound.start();
}
WHEN START/STOP:
if(sound.isPlaying()) {
sound.stop();
} else {
sound.reset();
sound.setDataSource(yourURL); //or InputStream etc.
sound.prepare();
sound.start();
}
Also you can use sound.seekTo(time) to skip to a position.
Remember when you want to play a new sound(or restart) you should first reset, setDataSource, prepare and then start it.
EDIT: get the FileDescripter
AssetManager assetManager=Context.getAssets();
AssetFileDescriptor fileDescriptor = assetManager.openFd("a2.mp3");
mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor());
EDIT: I haven't found a way to turn raw file into filedescriptor so I use the static method of MediaPlayer
MediaPlayer mediaPlayer = MediaPlayer.create(Activity.this,R.raw.a1);
mediaPlayer.setOnCompletionListener(new musicCompletionListener());
mediaPlayer.start();
private class musicCompletionListener implements OnCompletionListener {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
}
alse release the mediaplayer when stop it.
Have you tried resetting the MP?
if (sound.isPlaying()) {
sound.stop();
} else {
sound.reset();
sound.prepare();
sound.start();
}
Edited...
The full state diagram is here: http://developer.android.com/reference/android/media/MediaPlayer.html

Youtube Video Playing issue in Android - Code Attached

This is a critical issue pertaining to an application we did. The code snippet attached here was working like a charm for the past several months. All of a sudden, it gives us the message in mediaplayer that video cannot be played.
Can anyone please suggest what need to be done, in order that this code will work for me by playing the video with no hassles.
Looking forward for your valuable comments, help and suggestions,
Please follow this link in order to view the code which was working perfectly -- http://pastebin.com/NVT8eBC0
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class videoact extends Activity implements OnPreparedListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaController mc = new MediaController(this);
VideoView vv = (VideoView)findViewById(R.id.VideoView01);
try
{
Uri ur = Uri.parse("http://youtube.com/get_video?video_id=ZmX7zLCrcAI&t=vjVQa1PpcFPmrj_j5y370BhPYfq3qHoWsFICYcBqEl4%3D&asv=&fmt=18");
vv.setVideoURI(ur);
vv.setMediaController(mc);
vv.requestFocus();
vv.start();
mc.show();
}
catch(Exception e)
{
System.out.print(e.getMessage() + "error");
}
}
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
}
You can't play YouTube videos like that. Use the Android YouTube Player Api or the IFrame API in a WebView.
Using the get_video endpoint is against youtube's terms of service.
https://www.youtube.com/static?template=terms
You agree not to access Content through any technology or means other than the video playback pages of the Service itself, the Embeddable Player, or other explicitly authorized means YouTube may designate.

Categories

Resources