im making a music app just for fun. I can read all my music files from sd card but MediaPlayer wont play the sound. I have the path to the file which i pass to the media player with setDataSource but nothing happens and i get no exceptions. Here is the code im using.
Uri songUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
setUpViews();
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(songUri.toString());
mp.prepare();
} catch (IllegalArgumentException e) {
Toast.makeText(this, "ILLEGAL ARGUMENT EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (SecurityException e) {
Toast.makeText(this, "SECURITY EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(this, "ILLEGAL STATE EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "IO EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
mp.start();
Log.d("URI AFTER SET UP", songUri.toString());
}
As i said before nothing happens when i open this activity but i still get all the Log.d in the console. Is there any more configurations for the media player to play the music? Thanks in advance.
setDataSource() requires a path argument . You are passing the entire uri as string. Try this :
mp.setDataSource(songUri.getPath());
mp.prepare();
mp.start();
Moreover, if you are trying to access a file with content:// uri, it won't work. You'll have to find the real path to the file, i.e file:// uri.
I think you have to add setAudioStreamType to your MediaPlayer Object. You can add this before mp.setDataSource(your_URI); like below
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
There other types, you can choose AudioManager.STREAM_MUSIC for Music Player
I just solved the problem, and i just dont know why it works. What i did was to put a button to stop the music being played. I dont understand why it works so if someone could explain why it does i'd be thanksfull.
get the path of song by querying MEDIASTORE-EXTERNAL_URI.And this field MEDIASTORE.AUDIO.MEDIA.DATA will give u the path of the song(which is string). U can set it directly to mediaplayer.setDataSource(Your_path_from_mediastore) .It will work fine than.
Related
I am trying to create Mediaplayer session with given uri. but it causes NullpointerException.
Uri uri = Uri.parse(path);
// Creating MediaPlayer with given song's URI
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(this, uri);
try {
// Setting the MediaPlayer Listener
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
changeSeekbar();
}
});
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Given Logcat:
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference
Could you Tell me What i am doing wrong ? Thanks.
There are two ways to write this code, both tested on the device
First of all, make sure you handle android.permission.READ_EXTERNAL_STORAGE correctly and you really have correct Uri.
MediaPlayer.create(this, uri); will fail if either context or uri are invalid.
MediaPlayer.create(this, uri); which itself already prepares player so you don't need .prepareAsync() in this situation. and your code is good to go.
another way:
mediaPlayer = new MediaPlayer(); // hence, we don't use .create, manually instantiate
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.setOnPreparedListener(mp -> {
mediaPlayer.start();
});
/* use async, if you don't want to block UI thread
keep in mind, this should be called after setting listener
because it might prepare even until the listener has been set */
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Try this :
Uri uri = Uri.parse(path);
mediaPlayer = new MediaPlayer();
try {
// mediaPlayer.setDataSource(String.valueOf(uri));
mediaPlayer.setDataSource(MainActivity.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
I'm trying to play a .wav audio in Android from assets folder.
The problem is that there is no error but the audio isn't playing.
Here's my code
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd("success.wav");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.setLooping(false);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
Your code is ok, i checked, its working.
Please ensure the \assets folder is placed
correctly(\app\src\main\assets)
Check your device volume level.
Play success.wav in PC media player and ensure it is audible.
Note:
Using device volume controls:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
If your app is media related, use setVolumeControlStream API at your onResume() of activity or fragment and use device volume hard keys to increase/decrease volume. This set the application to only modify stream_music volume /media volume, otherwise it will modifiy ring volume.
Ref:https://developer.android.com/guide/topics/media-apps/volume-and-earphones
Did You try this?
MediaPlayer mediaPlayer = null;
public void playSound(final Context context, final String fileName) {
mediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd(fileName);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
} catch (final Exception e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
I'm totally new to Android Development and to Android devices in general, so I don't know how things are working here.
I want to make an app that will stream music from my url and still playing the song after I minimize the application.
I searched my question but a lot of answers were for mp3 songs or other types, but my url is from a live radio so it isn't one song only.
One of the answers that I found and were good for my problem was this and uses this code:
Uri myUri = Uri.parse("your url here");
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(myUri, "audio/*");
startActivity(intent);
This prompt me to choose a music player.
Is there any way to just press my "play" button and hear the music?
In my iOS app I use this code and I can start and stop the streaming music whenever I want without an external player:
func prepareToPlay() {
let url = URL(string: "myUrl")
playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)
player?.play()
}
Thanks in advance
EDIT
After suggested in comments and answer I tried to play it with MPlayer, I made a function and I called it when I tapped my button like this:
public void playM() {
String url = "http://android.programmerguru.com/wp-content/uploads/2013/04/hosannatelugu.mp3";
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
But I get an error (the fourth message) and I saw in the logs this:
Unable to create media player
prepareAsync called in state 1, mPlayer(0x0)
start called in state 1, mPlayer(0x0)
error (-38, 0)
Intent with ACTION flag is intended to open another app in most cases. Since you don't need it. You want your own custom player. So Android has a Media Player class for such scenarios.
Create instance of it and pass your stream-URL. Now, set the data-source and call prepare() after that in onBtnClickListener() start the music by calling mp.start()
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
P.S: Catch all the exceptions and make sure the PERMISSIONS in manifest file
Intent is using only for sending some data between activities/services and system. It won't play the music. It don't do anything except saying to some activity what to do. You need the mechanism which will play your multimedia stream. You should use MediaPlayer class for playing multimedia inside your application.
Here's some tutorial, how to play music from stream: http://programmerguru.com/android-tutorial/android-mediaplayer-example-play-from-internet/
I have a Uri formed like
Uri sound = Uri.parse("file:///pathinmymobile/a?.mp3")
but because of the question mark, in MediaPlayer creation throws a setDataSource problem. I've also tested without the "file://", and with
URLEncoder.encode("file:///pathinmymobile/a?.mp3", "UTF-8").
and other more combinations. Is it possible to play a file containing special characters as question marks ?
If your file is in Android assets folder. This might help
try {
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor descriptor = getAssets().openFd("intro.mp3");
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.setLooping(true);
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
I'm a Beginner in android programming and I want to programming mp3 app to call some mp3 files from URL, so when I show "Media Player" in android developer I put the URL in the setDataSource and it's work fine, but the problem is the Activity take a lot of time to display it and in the sometimes app will be crashed. This is the part of my code :
file_url = Mp3_Linkes[num];
//Set Source
try {
mp.setDataSource(file_url);
} catch (Exception e) {
Toast.makeText(this, "Source Error !!", Toast.LENGTH_LONG).show();
}
//Prepare
try {
mp.prepare();
}catch(Exception e)
{
Toast.makeText(this, "Prepare Error !!", Toast.LENGTH_LONG).show();
}
//Start
mp.start();
Your activity is blocking because you are calling prepare on your Main Thread (UI thread)
Instead You can use prepareAsynch and OnPreparedListener to start specially when loading from remote source:
code :
try {
mp.setDataSource(file_url);
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
mp.prepareAsync();