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.
Related
I am not sure where I have missed something, I expect the playPauseButton to respond when I click it but nothing happens when I do. I have noticed some errors in my debug console log, which are mostly related to mediaPlayer, but I don't exactly know what they mean, since an quite new to android programming! Below is my debug console log, and a bit of related code:
// Removed Logcat!!
Some code related from a class Player.java:
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.util.Log;
import java.io.IOException;
public class Player {
// Creating new MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
// Creating a public static player as reference to this Player class
public static Player player;
String url = "";
public Player () {
this.player = this;
}
public void playStream (String url) {
if (mediaPlayer != null) {
try {
mediaPlayer.stop();
} catch (Exception e) {
}
// Releasing everything from the mediaPlayer
mediaPlayer = null;
}
// Creating new Media Player
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// Try & Catch errors
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pausePlayer () {
try {
mediaPlayer.pause();
} catch (Exception e) {
Log.d("EXCEPTION", "Failed to pause Media Player");
}
}
public void playPlayer () {
try {
mediaPlayer.start();
} catch (Exception e) {
Log.d("EXCEPTION", "Failed to start Media Player");
}
}
public void togglePlayer () {
try {
if (mediaPlayer.isPlaying())
pausePlayer();
else
playPlayer();
} catch (Exception e) {
Log.d("Exception", "Failed to toggle Media Player");
}
}
}
the other related code from MainActivity.java
public class MainActivity extends AppCompatActivity {
static FloatingActionButton playPauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playPauseButton = (FloatingActionButton) findViewById(R.id.fab);
playPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Songs location on our server
String url = // "*My website/file.mp3";
// Passing above url to our MediaPlayer
if (Player.player == null)
new Player();
Player.player.playStream(url);
}
public static void flipPlayPauseButton (boolean isPlaying) {
if (isPlaying) {
playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
} else {
playPauseButton.setImageResource(android.R.drawable.ic_media_play);
}
}
Try for example:
playPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(video.isplaying()){pause function()}
else{play function()}
}
});
Okay, I'd like to thank MohammadMoeinGolchin, who has helped me figure this out. It so happen's that I did not complete my function inside of my public void onClik(View view) function. But you will see that is is written somewhere in a separate Player.java class. So to resolve this, what I did instead, is to call the togglePlayer() function inside my onClick(View view) like this:
#Override
public void onClick (View view) {
Player.player.togglePlayer();
}
I'm trying to get this stream to play:
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://knhc-ice.streamguys1.com/live");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
But when the application runs it is giving me this error:
2019-03-17 17:01:05.035 5924-5924/com.example.android.c895 W/System.err: java.io.IOException: setDataSource failed.: status=0x80000000
I understand that the link that I am passing into the media player is just a single player, but I want that player to automatically play and be passed to the MediaPlayer. Is there anyway I can do this?
What I was able to figure out was put my MediaPlayer on Async Task(background thread) on my application.
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
b = (ImageButton) bottomSheet.findViewById(R.id.imageButton);
new PlayerTask().execute(s);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
if(started)
{
mediaPlayer.start();
}
}
});
class PlayerTask extends AsyncTask<String, Void, Boolean>
{
#Override
protected Boolean doInBackground(String... strings) {
try
{
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch(IOException e)
{
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean)
{
super.onPostExecute(aBoolean);
mediaPlayer.start();
}
}
Since the codes are almost identically the same, could anyone answer why this works and not just on the main thread?
I am new in android development and learning android apps development. I have created a very basic and simple Flashlight for android device. I am facing the issue when i run the app it takes some time to run like if i press turn on flash light it will take some time (half sec or less but it take some time), i didn't use wait() method in my app. How to run it really fast like user click on it flash turn on or turn off?
public class MainActivity extends AppCompatActivity {
private ImageButton imageButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
private Camera.Parameters params;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.switch_btn);
//Check that Device has supports flash or not
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash){
//If device does not supports Flash
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your current device does not support to Little Flashy! ops");
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Close application
finish();
}
});
alert.show();
return;
}
//Get the Camera
getCamera();
//Display button image
toggleButtonImage();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else
{
turnOnFlash();
}
}
});
}
private void toggleButtonImage() {
if (isFlashOn){
imageButton.setImageResource(R.drawable.btn_switch_on);}
else {imageButton.setImageResource(R.drawable.btn_switch_off);}
}
private void getCamera() {
if (camera == null){
try{
camera = camera.open();
params = camera.getParameters();
}catch (RuntimeException e){
Log.d("Camera Error.", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
private void playSound() {
if (isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);}
else {
mp= MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
//turn off flash when on Pause called
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (hasFlash) turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
getCamera();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null){
camera.release();
camera = null;
}
}
}
Before you turn the flash on and off, you call the playSound method, which uses the MediaPlayer. this method is slow and causes your delay. First try to remove it (by commenting it out) and see the difference. Next, you can try to run it from a thread.
Yes, you can ignore the sound feature for current time. Or if you really want this feature than use it through Thread it will show no lag or delay in your app while user turn on or turn off flash.
I'm relatively new to android development and I'm trying to make a game in Android Studio where I want background music to play. Here is my code for the service:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.backgroundmusic);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
player.pause();
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
player.pause();
}
}
And in the activity where I want to initialise the backgroundmusic
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
which is placed in the onCreateMethod. When I open the activity where I call the service to play the music, nothing happens, total silence.
For some further details: the backgroundmusic file is in a .mp3 format and the phone on which I do my testing is a Nexus 6 running the latest version of Marshmallow.
I'm probably missing something obvious, can anyone point it out for me and/or give any tips on how to do it better in the future? Thanks in advance.
try this piece of code for running the music on the start up
public class start extends Activity {
MediaPlayer intro;
#Override
protected void onCreate(Bundle Start) {
// TODO Auto-generated method stub
super.onCreate(Start);
setContentView(R.layout.start);
intro = MediaPlayer.create(start.this,R.raw.SONGNAME);
intro.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStart = new Intent("com.example.main.MAIN");
startActivity(openStart);
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
intro.release();
finish();
}
and make sure that the music file is located in the correct folder (raw)
Try to add a prepare-Listener:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "preparation Completed ...playing ");
player.start();
}
});
I think the setVolume is by default handled with a float (0=off, 1=max). Check your log output too. Sometimes the MediaPlayer is reporting a error-code.
EDIT / Second approach:
Did you added this line to your manifest (inside application tag)?
<application
... >
<service android:name="BackgroundSoundService" android:enabled="true"></service>
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;
}
}