I copied song.mp3 to my project's assets directory and wrote this code:
private MediaPlayer mp;
Uri uri = Uri.parse("file:///android_asset/song.mp3");
mp=MediaPlayer.create(this, uri);
After running the create statement, the variable mp is null. What is wrong?
Thanks.
Try this:
try {
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();
}
catch (IllegalArgumentException e) { }
catch (IllegalStateException e) { }
catch (IOException e) { }
Try this and see if any exceptions are caught:
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(this, uri);
}
catch (NullReferenceArgument e) {
Log.d(TAG, "NullReferenceException: " + e.getMessage());
}
catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException: " + e.getMessage());
}
catch (IOException e) {
Log.d(TAG, "IOException: " + e.getMessage());
}
catch (IllegalArgumentException e) {
Log.d(TAG, "IllegalArgumentException: " + e.getMessage());
}
catch (SecurityException e) {
Log.d(TAG, "SecurityException: " + e.getMessage());
}
The exception caught will explain what is going wrong in your create. According the the docs, the static create method is just shorthand for what is in the try block above. The major difference that I can see is that the static method create doesn't throw while setDataSource does.
You'd better try this on the devices running on Android N or the latest:
try {
AssetFileDescriptor afd = getAssets().openFd("*.mp3 / *.mp4");
player = new MediaPlayer();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
player.setDataSource(afd);
player.prepareAsync();
player.start();
} catch (...) {
}
else, do like the best answer below.
Related
I am using MediaPlayer in my app. I am following the following tutorial
http://blog.lemberg.co.uk/surface-view-playing-video
Here's part of the code
Surface surface = new Surface(surfaceTexture);
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(FILE_URL));
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
// Play video when the media source is ready for playback.
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e) {
Log.d(TAG, e.getMessage());
} catch (SecurityException e) {
Log.d(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
Everything works fine except the video does not loop. When I set the data source a file from assets it loops just fine. But when I stream the video from URL it does not loop.
Thanks
I have a res/raw folder made in the project in which I placed a single file t.mp4. I intended to use a textureview to play the video file using the SurfaceTextureAvailable listener by implementing the relevant interface.
I created a mediaplayer object in the onSurfaceTextureAvailable method
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
Surface s = new Surface(surface);
Log.d("debug", "Surface Texture Available");
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(this, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.t));
Log.d("debug", "data source set");
mMediaPlayer.setSurface(s);
Log.d("debug", "Surface set");
mMediaPlayer.prepare();
Log.d("debug", "prepared");
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
Log.d("debug", "listeners set");
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("error", e.getMessage());
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("error", e.getMessage());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("error", e.getMessage());
}
}
This worked fine the first few times I ran the app, but after working on another (non-related) part of my project, it suddenly stopped working.
In the log, I keep getting an IOException, which I am 90% sure is because the application cannot find the file.
What happened?
Cheers
You can use MediaPlayer.create() in place of new MediaPlayer()/setDataSource() to easily create a MediaPlayer for a raw resource:
mMediaPlayer = MediaPlayer.create(this, R.raw.t);
public void playClickSound() {
AssetFileDescriptor afd;
MediaPlayer sound = new MediaPlayer();
try {
sound.setAudioStreamType(AudioManager.STREAM_MUSIC);
afd = getAssets().openFd("click.mp3");
sound.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
sound.prepare();
sound.start();
} catch (IllegalStateException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
This is my code for playing sound. I call this method on a few buttons in mu GUI.
It works fine the first time i press the button, but second time i get IllegalStateException.
What should I do to make this work?
You need to manage the life-cycle of the Media Player. Following the below flow, should work out:
RefreshPlayer()
{
if (mediaPlayer != null) {
{
mediaPlayer.stop();
mediaPlayer.reset();
}
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getSherlockActivity(),
Uri.fromFile(new File(VidPath)));
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
Can anyone please suggest me how to play live radio stream url in android. Someone who has experience in playing live radio url in android.
Thanks
try
{
MediaPlayer media = new MediaPlayer();
media.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
media.setDataSource("http://indiespectrum.com:9000");
media.prepare();
media.start();
}
catch(Exception e)
{
//Getting Exception
}
public void startRadio(String streamUrl) {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
}
});
try {
mPlayer.setDataSource(streamUrl);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(getClass().getName(), "IllegalArgumentException");
} catch (IllegalStateException e) {
Log.e(getClass().getName(), "IllegalStateException");
} catch (IOException e) {
Log.e(getClass().getName(), "IOException");
}
}
Quick copy paste ..
So I have a small audio file in my assets folder and I wanted to open a InputStream to write to a buffer, then write to a temporary File, then I open up the MediaPlayer to play that temporary File. Problem is, when the media player hits mp.Prepare(), it doesn't play and never reaches the toast. Has anyone ever done this before?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputStream str;
try {
str = this.getAssets().open("onestop.mid");
Toast.makeText(this, "Successful Input Stream Opened.", Toast.LENGTH_SHORT).show();
takeInputStream(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end on create
public void takeInputStream(InputStream stream) throws IOException
{
//fileBeingBuffered = (FileInputStream) stream;
//Toast.makeText(this, "sucessful stream conversion.", Toast.LENGTH_SHORT).show();
try
{
convertedFile = File.createTempFile("convertedFile", ".dat", getDir("filez", 0));
Toast.makeText(this, "Successful file and folder creation.", Toast.LENGTH_SHORT).show();
out = new FileOutputStream(convertedFile);
Toast.makeText(this, "Success out set as output stream.", Toast.LENGTH_SHORT).show();
//RIGHT AROUND HERE -----------
byte buffer[] = new byte[16384];
int length = 0;
while ( (length = stream.read(buffer)) != -1 )
{
out.write(buffer,0, length);
}
//stream.read(buffer);
Toast.makeText(this, "Success buffer is filled.", Toast.LENGTH_SHORT).show();
out.close();
playFile();
}catch(Exception e)
{
Log.e(TAG, e.toString());
e.printStackTrace();
}//end catch
}//end grabBuffer
public void playFile()
{
try {
String path = convertedFile.getAbsolutePath();
mp = new MediaPlayer();
mp.setDataSource(path);
Toast.makeText(this, "Success, Path has been set", Toast.LENGTH_SHORT).show();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
Toast.makeText(this, "Media Player prepared", Toast.LENGTH_SHORT).show();
mp.start();
Toast.makeText(this, "Media Player playing", Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}//end playFile
Fixed it. Turns out that after writing the buffer in the temporary file created by "File," you can then open that file using a FileInputStream, then proceed to play it shown below. Thanks for all your help guys.
mp = new MediaPlayer();
FileInputStream fis = new FileInputStream(convertedFile);
mp.setDataSource(fis.getFD());
Toast.makeText(this, "Success, Path has been set", Toast.LENGTH_SHORT).show();
mp.prepare();
mp.start();
This is the code that worked for me
//preserved to stop previous actions
MediaPlayer lastmp;
public void playSound(String file) {
try {
if (lastmp!=null) lastmp.stop();
MediaPlayer mp = new MediaPlayer();
lastmp = mp;
AssetFileDescriptor descriptor;
AssetManager assetManager = act.getAssets();
descriptor = assetManager.openFd(fileName);
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
the file shoud be on the assets folder