I am creating a sound board and after clicking about 30 different sounds it stops working; I believe android is running out of memory. Below is my code. How can I implement .release() so that when the sound is done playing it is released? I don't really care if two things play at the same time; the clips are t0o short for this to be possible. I would just like to get my code set.
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
I have done a lot of searching around but due to my lack of java/android knowledge I have not been able to get anything to work. Thanks in advance, let me know if anyone needs anymore code.
I left a comment, but I'll post an answer to show what I mean anyway...
The idea is that you have a set number of MediaPlayer instances that you can use. That way you never exceed the maximum number of instances. The array should be the length of the number of concurrent sounds you expect to be able to hear. If the sounds are local files, the length of time it takes to prepare the sounds should be almost negligible, so calling create inside the click handler should not result in terrible performance. Each of your buttons is associated with a particular resource, I suppose, so I set up a helper method to create and play the sounds for each button in the same way.
public class soundPageOne extends Activity {
private MediaPlayer[] mPlayers = new MediaPlayer[2];
private int mNextPlayer = 0;
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
Button playSound1 = (Button)this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSound(R.raw.peter1);
}
});
}
public void onDestroy() {
super.onDestroy(); // <---------------------- This needed to be there
for (int i = 0; i < mPlayers.length; ++i)
if (mPlayers[i] != null)
try {
mPlayers[i].release();
mPlayers[i] = null;
}
catch (Exception ex) {
// handle...
}
}
private void startSound(int id) {
try {
if (mPlayers[mNextPlayer] != null) {
mPlayers[mNextPlayer].release();
mPlayers[mNextPlayer] = null;
}
mPlayers[mNextPlayer] = MediaPlayer.create(this, id);
mPlayers[mNextPlayer].start();
}
catch (Exception ex) {
// handle
}
finally {
++mNextPlayer;
mNextPlayer %= mPlayers.length;
}
}
}
Create a class, say AudioPlayer with a SoundPool variable. Setup a constructor to initialise the AudioPlayer object and create a Play method. SoundPool works better for short sounds played many times and does not require you to release.
public class AudioPlayer {
private SoundPool sPool = new SoundPool(Integer.MAX_VALUE, AudioManager.STREAM_MUSIC, 0);
public AudioPlayer(Context c, int id){
sounds.put("1",sPool.load(c, id, 1));
}
public void play(Context c) {
sPool.play("1", 1, 1, 1, 0, 1f);
}
}
So your class should look like
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer ap = new AudioPlayer(this, R.raw.sound);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ap.play();
}
});
Could you use a MediaPlayer.OnCompletionListener?
Something like:
public class soundPageOne extends Activity implements MediaPlayer.OnCompletionListener {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final MediaPlayer pg1 = MediaPlayer.create(this, R.raw.peter1);
//***set the listener here***
pg1.setOnCompletionListener(this);
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.start();
}
});
}
//***this code will be executed once the sound finishes playing***
#Override
public void onCompletion(MediaPlayer mp) {
//log messages, other things can go here
mp.release();
}
Try something like this
Your activity class:
public class soundPageOne extends Activity {
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.soundsone);
final AudioPlayer pg1 = new AudioPlayer();
Button playSound1 = (Button) this.findViewById(R.id.peter1Button);
playSound1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pg1.play(this, R.raw.sound);
}
});
}
This is another Java Class:
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Context c, int sound) {
stop();
mPlayer = MediaPlayer.create(c, sound);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
stop();
}
});
mPlayer.start();
}
public boolean isPlaying() {
return mPlayer != null;
}
}
Related
I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed
I have an activity (not my main activity) that plays some sounds and draw some graphics in a runnable thread. There is an imagebutton with which I'm supposed to suspend and resume the thread. But whatever I try the thread just runs on. I'm totally stuck! Please help.
public class PlayInterval extends Activity {
private Handler customHandler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playinterval);
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton);//Play/Pause
playPauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onPlayPauseClicked(playPauseButton,(String)playPauseButton.getTag());
}
});
customHandler = new Handler();
new Thread(new Task()).start();
}
#Override
public void onBackPressed() {
customHandler.removeCallbacksAndMessages(null);
finish();
}
class Task implements Runnable {
#Override
public void run() {
// Do really cool stuff
// and even cooler stuff
customHandler.postDelayed(this, 100);
}
}
private void onPlayPauseClicked(ImageButton playPauseButton, String status) {
if (status == "playing") {
playPauseButton.setTag("paused");
customHandler.removeCallbacksAndMessages(null); //TODO suspend here not working!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
playPauseButton.setImageResource(getResources().getIdentifier("pause_image", "drawable", getPackageName()));
} else {
playPauseButton.setImageDrawable(getDrawable(getResources().getIdentifier("pause_image", "drawable", getPackageName())));
}
} else {
playPauseButton.setTag("playing");
customHandler.postDelayed(this, 100); //TODO resume here not working!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
playPauseButton.setImageResource(getResources().getIdentifier("play_image", "drawable", getPackageName()));
} else {
playPauseButton.setImageDrawable(getDrawable(getResources().getIdentifier("play_image", "drawable", getPackageName())));
}
}
}
}
I never did get an answer so after trial and error I came up with this. I've red quite alot here on StackOverflow and what I understand this is NOT the way it is supposed to be done. But it is working very well, so if anyone could explain why one shouldn't use syncronized methods like this and provide a better answer I would be thankful.
Cheers
public class PlayInterval extends Activity {
private Handler customHandler;
Boolean isRunning;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playinterval);
final ImageButton playPauseButton = (ImageButton)findViewById(R.id.playPauseButton);//Play/Pause
playPauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onPlayPauseClicked(playPauseButton);
}
});
customHandler = new Handler();
isRunning=true;
new Thread(new Task()).start();
}
#Override
public void onBackPressed() {
customHandler.removeCallbacksAndMessages(null);
finish();
}
class Task implements Runnable {
#Override
public void run() {
if (isRunning == true){
// Do really cool stuff
// and even cooler stuff
} else {
// it is paused
}
customHandler.postDelayed(this, 100);
}
private syncronized void onPlayPauseClicked(ImageButton playPauseButton) {
if (isRunning==true) {
isRunning=false;
playPauseButton.setImageResource(getResources().getIdentifier("play_image", "drawable", getPackageName()));
} else {
isRunning=true;
playPauseButton.setImageResource(getResources().getIdentifier("pause_image", "drawable", getPackageName()));
}
}
}
I made a simple class that handles everything related to sound. Has an add, play, stop, release and releaseAll. How it works is that you have to add a song and then call play passing the name of the song you added. Anytime you need to stop, just call the stop function and pass the song's name as parameter and it should stop. My issue is that it isn't stopping even though it goes through stop().
Sound class:
public class Sound
{
private Map<String, MediaPlayer> songs = new HashMap<String, MediaPlayer>();
private MediaPlayer currentlyPlayingSong;
public Sound() {}
public void Add(int songId, String songName, Context context)
{
MediaPlayer song = MediaPlayer.create(context, songId);
songs.put(songName, song);
}
public void Play(String name, boolean shouldLoop)
{
MediaPlayer songToPlay = songs.get(name);
if ( songToPlay != currentlyPlayingSong && songToPlay != null)
{
currentlyPlayingSong = songToPlay;
currentlyPlayingSong.start();
currentlyPlayingSong.setLooping(shouldLoop);
}
}
public void Stop(String name)
{
MediaPlayer songToStop = songs.get(name);
if (songToStop != null)
{
songToStop.setLooping(false);
songToStop.stop();
}
}
public void Release(String name)
{
songs.get(name).release();
}
public void ReleaseAll()
{
LinkedList<MediaPlayer> _songs;
_songs = (LinkedList)songs.values();
for (int i = 0; i < _songs.size(); i++)
{
_songs.get(i).release();
}
}
}
On the activity's OnCreate I call Add then Play. Everything is fine until I try to call Stop from a fragment. Runs without any errors or exceptions, it simply doesn't stop.
Activity:
public class Main extends ActionBarActivity
{
private Sound sound = new Sound();
private static boolean isSoundOn = true;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isSoundOn = true;
sound.Add(R.raw.drajamainmenueddited, "mainMenuSong", this);
//endregion
//Hide upper action bar
getSupportActionBar().hide();
if (isSoundOn)
sound.Play("mainMenuSong", true);
}
public void SetIsSoundOn(Boolean isOn)
{
isSoundOn = isOn;
}
public boolean GetIsSoundOn()
{
return isSoundOn;
}
public Sound GetSoundObj()
{
return sound;
}
}
Fragment:
public class MainMenuFragment extends Fragment {
private ImageButton soundImgBtn;
private FragmentConfig fragmentConfig;
public MainMenuFragment()
{
fragmentConfig = new FragmentConfig();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//region Initiators
View view = inflater.inflate(R.layout.fragment_main_menu, container, false);
soundImgBtn = (ImageButton)view.findViewById(R.id.soundImgBtn);
//endregion
//region Listeners
soundImgBtn.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SoundImgBtnClick(v);
}
}
);
//endregion
//Changes audio img
if (((Main)getActivity()).GetIsSoundOn())
soundImgBtn.setImageResource(android.R.drawable.ic_lock_silent_mode_off);
else
soundImgBtn.setImageResource(android.R.drawable.ic_lock_silent_mode);
// Inflate the layout for this fragment
return view;
}
private void SoundImgBtnClick(View v)
{
//if sound is on and clicked, turn off
if (((Main)getActivity()).GetIsSoundOn())
{
((Main)getActivity()).SetIsSoundOn(false);
((Main)getActivity()).GetSoundObj().Stop("mainMenuSong");
soundImgBtn.setImageResource(android.R.drawable.ic_lock_silent_mode);
}
else
{
((Main)getActivity()).SetIsSoundOn(true);
((Main)getActivity()).GetSoundObj().Play("mainMenuSong", true);
soundImgBtn.setImageResource(android.R.drawable.ic_lock_silent_mode_off);
}
}
}
What I'm trying to do is emulate a mute button. Once clicked all sounds should be muted.
This is pretty much all I've coded, so far.
Cheers.
I suspect you're using different instances of MediaPlayer. You are allowed to do that BUT you must stop the song within the same instance.
About the code in Add():
MediaPlayer song = MediaPlayer.create(context, songId);
In Stop():
MediaPlayer songToStop = songs.get(name)
Note:
The above codes tell me you're using different instances of the MediaPlayer for one same song. The object song needs to be declared on a higher scope for you to access it and to stop the song.
Need to call release() method after stop() to free up resources.
try songToStop.release() instead
Got it to stop. My class had to be able to handle one song at a time and many fx at the same time. This is what I came up with.
Sound:
public class Sound
{
private static MediaPlayer currentlyPlayingSong,
currentlyPlayingFX;
public Sound() {}
public void PlayFX(int fxId, Context context, boolean shouldLoop)
{
MediaPlayer fx = MediaPlayer.create(context, fxId);
if (currentlyPlayingFX != fx)
{
StopFX();
currentlyPlayingFX = fx;
currentlyPlayingFX.start();
currentlyPlayingFX.setLooping(shouldLoop);
}
}
public void PlaySong(int songId, boolean shouldLoop, Context context)
{
MediaPlayer song = MediaPlayer.create(context, songId);
if (currentlyPlayingSong != song)
{
StopSong();
currentlyPlayingSong = song;
currentlyPlayingSong.start();
currentlyPlayingSong.setLooping(shouldLoop);
}
}
public void StopFX()
{
if (currentlyPlayingFX != null)
{
currentlyPlayingFX.stop();
currentlyPlayingFX.release();
currentlyPlayingFX = null;
}
}
public void StopSong()
{
if (currentlyPlayingSong != null)
{
currentlyPlayingSong.stop();
currentlyPlayingSong.release();
currentlyPlayingSong = null;
}
}
}
This is was based of what #The Original Android answered. Keep it on a single instance.
Thanks for the help.
here's my code for a very basic android sound player, on button press I expect a sound to play, or an IOException to be caught - seems simple enough. Instead I get "QCMediaPlayer mediaplayer NOT present", so how am I meant to play my track if there's no player available - & what should I do as an alternative?
I understand it's already been raised, but no trivial solution was given.
public class MainActivity extends Activity {
private MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button motivate = (Button) this.findViewById(R.id.motivate);
motivate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // On click randomly select a sound then play it
try {
play();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void stop() {
if (player != null) {
player.release();
player = null;
}
}
public void play() throws IOException {
stop();
int[] sound = {R.raw.a, R.raw.b, R.raw.c, R.raw.d, R.raw.e, R.raw.f, R.raw.g, R.raw.h, R.raw.i, R.raw.j, R.raw.k, R.raw.l, R.raw.m, R.raw.n, R.raw.o};
player = MediaPlayer.create(MainActivity.this, sound[0]);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
stop();
}
});
}
}
You can try this one:https://bitbucket.org/edwardcw/libvlc-android-sample
We used it for stream playback
Okay so the answer to this was actually rather simple. MediaPlayer is an import that only 8/10 will work depending on your flavour of android and kernel. A constant is SoundPool; this will load and play a sound as required.
I am having a strange issue playing a VideoView. I have done my best to simplify the code as much as possible. Below are 4 classes: A, MirrorActivity, Replay, and MyTask. Assume the following occurs in this order:
A is created.
MirrorActivity() is created.
Inside MirrorActivity()'s onCreate(), that instance calls A's setMirrorActivity() to allow A to have a reference to it.
A's doThis() method is called, which executes mirrorActivity.playVideo().
playVideo() is executed.
Replay's executeVideo() is called.
MyTask is executed.
For some strange reason, when the above is executed, the video does not play. However, when the myButton ImageButton is pressed inside MirrorActivity, it plays the video on command. Both of these seem to be doing the same thing by calling MirrorActivity's playVideo(). Do you know why the above does not execute?
A
public class A{
private static final A instance = new A();
private MirrorActivity mirrorActivity;
public static A getInstance() {
return instance;
}
public void setMirrorActivity(MirrorActivity mirrorActivity) {
this.mirrorActivity = mirrorActivity;
}
public void doThis(String url){
mirrorActivity.playVideo(String url);
}
}
MirrorActivity
public class MirrorActivity extends Activity {
public static String VIDEO_URL = "example.mp4";
public VideoView mVideoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overlay_gradient);
// Set Mirror Activity
A.getInstance().setMirrorActivity(this);
mVideoView = (VideoView) findViewById(R.id.mirrorVideoView);
MyTask vTask = new MyTask(mVideoView);
ImageButton myButton = (ImageButton) findViewById(R.id.myButton);
myButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
MirrorActivity.this.playVideo(MirrorActivity.VIDEO_URL);
}
});
}
public void playVideo(String videoURL)
{
MyTask mt = new MyTask(mVideoView);
Replay.executeVideo(MirrorActivity.VIDEO_URL,
this,
mVideoView,
mt);
}
}
Replay
public class Replay{
public static void executeVideo(String uri, Activity activity, VideoView vid, MyTask mt)
{
vid.setMediaController(new MediaController(activity););
vid.setVideoURI(Uri.parse(uri));
mt.execute();
}
}
MyTask
public class MyTask extends AsyncTask<Void, Integer, Void> {
private VideoView video;
private int duration = 0; // in milliseconds
public MyTask(VideoView vid) {
video = vid;
}
#Override
protected Void doInBackground(Void... params) {
video.start();
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
duration = video.getDuration();
}
});
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
I think UI element cannot access in doInBackground . And also start() after every declaration.
Try this method too.
private MediaController ctlr;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_overlay_gradient);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
// Set Mirror Activity
A.getInstance().setMirrorActivity(this);
mVideoView = (VideoView) findViewById(R.id.mirrorVideoView);
Uri uri=Uri.parse(videourl or video path);
mVideoView .setVideoURI(uri);
mVideoView .setVideoPath(videourl);
ctlr=new MediaController(this);
ctlr.setAnchorView(video);
ctlr.setMediaPlayer(video);
mVideoView .setMediaController(ctlr);
mVideoView .requestFocus();
mVideoView .start();
}
Omg. I believe I found the solution. I'm sorry to those who were investigating, but here is what I did to get it to work both ways. Pressing imageButton and calling A.doThis() will be able to play the video now.
I modified MirrorActivity's playVideo() function to use the following:
public void playVideo(final String videoURL)
{
Runnable runnable = new Runnable(){
#Override
public void run()
{
MyTask mt = new MyTask(mVideoView);
Replay.executeVideo(videoURL,
MirrorActivity.this,
mVideoView,
mt);
}
});
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(runnable);
}