MediaPlayer.create() returns null for filepath - android

I am trying to creae mediaplayer from file path
private void play(String path) {
MediaPlayer player = null;
if (path.startsWith("assets/music")) {
path = path.replace("assets/", "");
AssetFileDescriptor afd;
try {
afd = mActivity.getAssets().openFd(path);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
player.prepare();
} catch (IOException e) {
Log.e(TAG, e.toString());
}
} else {
player = MediaPlayer.create(mActivity, Uri.parse(path));
}
if (player != null) {
player.setOnCompletionListener(releaseListener);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(TAG, "mp error: " + what + ", extra: " + extra);
return true;
}
});
player.start();
mPlayer = player;
}
}
from assets path it works but MediaPlayer.create(mActivity, Uri.parse(path)); always returns null
full path is
/storage/emulated/0/Download/Buzzer - 1.mp3
assets path is
assets/music/Buzzer - 1.mp3

If you are saying that the value of path that you are passing to Uri.parse(path) is /storage/emulated/0/Download/Buzzer - 1.mp3, that is not a valid Uri. Notably, there is no scheme. Either:
Pass in a File that points to your desired file and use Uri.fromFile(), or
Ensure that path has a scheme (e.g., file:///storage/emulated/0/Download/Buzzer - 1.mp3)

Related

Do you know why mediaplayer runonuithread doesn't work?

I am trying to run Android's MediaPlayer using runOnUiThread. I did not caught any exception with setDataSource. But after that, nothing happens with MediaPlayer. It should give callback as surface changed and onPrepared.
It seems MediaPlayer doesn't support this way.
If it is true, are there any workarounds ?
I need this kind of logic because I need to get info with network query which is blocked. I need to run onSuccess from that.
What is your suggestion for this? Thanks very much!
onResume()
{
getInfo(xxx);
}
void getInfo(url, new DataListener() {
#Override
public void onDataSuccess(xxx) {
playVideoOnSuccess(xxx);
}
}
public void playVideoOnSuccess(xxx)
{
myBaseActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
mPlayerListener = new VideoPlayerListener(null, content);
// create new mediaplayer
mVideoPlayer = VideoPlayer.getInstance();
mVideoPlayer.setVideoPlayerListener(mPlayerListener);
// setDataSource
mVideoPlayer.consumeContent(content);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Here is a sample code that i used to play video hope this might help you in some way
public class VideoViewDemo extends Activity {
private static final String TAG = "VideoViewDemo";
private String current;
/**
* TODO: Set the path variable to a streaming video URL or a local media
* file path.
*/
private String path = "http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pete%20bio_4.mp4";
private VideoView mVideoView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.surface_view);
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
}
private void playVideo() {
try {
// final String path = path;
Log.v(TAG, "path: " + path);
if (path == null || path.length() == 0) {
Toast.makeText(VideoViewDemo.this, "File URL/path is empty",
Toast.LENGTH_LONG).show();
} else {
// If the path has not changed, just start the media player
if (path.equals(current) && mVideoView != null) {
mVideoView.start();
mVideoView.requestFocus();
return;
}
current = path;
mVideoView.setVideoPath(getDataSource(path));
mVideoView.start();
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
if (mVideoView != null) {
mVideoView.stopPlayback();
}
}
}
private String getDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
return path;
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
return tempPath;
}
}
}
This work for me

VideoView (building my own video view)

private void openVideo() {
if (mUri == null || mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the framework.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mContext.sendBroadcast(i);
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mIsPrepared = false;
Log.v(TAG, "reset duration to -1 in openVideo");
mDuration = -1;
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
mMediaPlayer.setDataSource(mContext, mUri);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
attachMediaController();
} catch (IOException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
return;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
return;
}
}
I got this code from GrepCode (VideoView).I would like to add Mute and unmute functions on my videoview hence am trying to create a new videoview.But due to this mContext variable i am not able to set the path for my mediaplayer.
Purpose of Mute and Unmute: To play other audios with the same audio..
I want to access the Mediaplayer for mute and unmute function and hence am not overriding my videoview class.
Am a newbie to android so suggest me some methods to achieve this. Thanks in advance.

How to get an audio filed packed in the apk archive to play in the app for android?

OK so I have a Woohoo.mp3 in my "assets" folder of my project
also after packing the .apk I do find it residing in the assets folder
audioPlayer("file:///android_assets/Woohoo.mp3");
or
audioPlayer("file://android_assets/Woohoo.mp3");
did not work...
here is my audioPlayer method:
public void audioPlayer(String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
Uri uri = Uri.parse(fileName);
try {
AssetManager manager = getBaseContext().getAssets();
AssetFileDescriptor descriptor = manager.openFd(fileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mp.setDataSource(descriptor.getFileDescriptor(), start, end);
//File file = new File(fileName);
//FileInputStream fis = new FileInputStream(file);
//mp.setDataSource(getBaseContext(),uri);
//mp.setDataSource(fis.getFD());
mp.prepare();
mp.start();
} catch(FileNotFoundException e){
Toast.makeText(getBaseContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
} catch (IOException e) {
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
};
}
I've been looking at this site and some other forums for few hours and tried a few methods and NONE of them worked for me....I wonder where I did wrong here... thanks
For using Assets u have to give only the FileName not the FilePath.
Try using only Woohoo.mp3

sorry, this video cannot be played in videoview?

freinds,
i am using following code to display a mp4 video in my application
and facing following problems
i have seen so many posts related to this issue on google and stackoverflow but every one giving his own suggestions and there is no common answer.
1) i cannot see video in emulator
2) in different phone sometime rarly video is played and most of the time it give above message.
my code
VideoView myVideoView = (VideoView)findViewById(R.id.videoview);
String viewSource ="http://dev.hpac.dev-site.org/sites/default/files/videos/about/mobile.mp4";
myVideoView.setVideoURI(Uri.parse(viewSource));
myVideoView.setMediaController(new MediaController(this));
myVideoView.requestFocus();
myVideoView.start();
any one guide me what is the solution to this problem
any help would be appreciated.
you can make a output stream using your file and get absolute path of stream then put path to video view
private String getDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
return path;
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
#SuppressWarnings("resource")
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
return tempPath;
}
}
and
public void initVideo() {
try {
if (!mVideoView.isPlaying()) {
if (url > playList.size() - 1) {
url = 0;
}
String[] playurl = (playList.get(url)).split("\\.");
String urlExtention = playurl[playurl.length - 1];
if (urlExtention.equals("mp4")) {
playVideo(playList.get(url));
} else if (urlExtention.equals("jpg")
|| urlExtention.equals("jpeg")) {
Intent intentShedule = new Intent(Default_Player.this,
ImagePlayer.class);
intentShedule.putExtra("imagePath", playList.get(url));
intentShedule.putExtra("urlValue", url);
intentShedule.putExtra("playlistType", playlistType);
intentShedule.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intentShedule);
finish();
} else {
Intent intentShedule = new Intent(Default_Player.this,
WebContentView.class);
intentShedule.putExtra("webPath", playList.get(url));
intentShedule.putExtra("urlValue", url);
intentShedule.putExtra("playlistType", playlistType);
intentShedule.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intentShedule);
finish();
}
}
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
System.out.println("set on error listner");
//do somthing if alert this video can not be played
return false;
}
});
mVideoView
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer vmp) {
playnew();
}
});
} catch (Exception e) {
}
// TODO Auto-generated method stub
}
use on error listner if alert this video can not be played
in eclipse emulator video not displayed that link from website(internet).
if you want to play a specific video. then make raw folder and give following path
String path1="android.resource://your package name/"+ R.raw.video name;
Uri uri=Uri.parse(path1);
videoView.setVideoURI(uri);

Play audio file from the assets directory

I have the following code:
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();
The problem is that, when I run this code, it starts playing all the audio files in the assets directory, in alphabetical order instead of just playing the audio file I requested. What am I doing wrong? Is there a better way to play audio files from the assets directory?
Follow-up question:
Is there a difference between keeping audio files in the assets directory and keeping them in the res/raw directory? Besides the fact that they don't get ids if they are in the assets directory. If I move the audio files to the res/raw folder then I have a problem with reusing MediaPlayers because there is no id parameter for setDataSource(). I can't find a good guideline for handling this kind of problem.
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
Your version would work if you had only one file in the assets
directory. The asset directory contents are not actually 'real files'
on disk. All of them are put together one after another. So, if you do
not specify where to start and how many bytes to read, the player will
read up to the end (that is, will keep playing all the files in assets
directory)
This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Here my static version:
public static void playAssetSound(Context context, String soundFileName) {
try {
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
start sound
startSound("mp3/ba.mp3");
method
private void startSound(String filename) {
AssetFileDescriptor afd = null;
try {
afd = getResources().getAssets().openFd(filename);
} catch (IOException e) {
e.printStackTrace();
}
MediaPlayer player = new MediaPlayer();
try {
assert afd != null;
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
}
Fix of above function for play and pause
public void playBeep ( String word )
{
try
{
if ( ( m == null ) )
{
m = new MediaPlayer ();
}
else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
m.stop();
m.release ();
m=null;
lastPlayed="";
return;
}else if(m != null){
m.release ();
m = new MediaPlayer ();
}
lastPlayed=word;
AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
long start = descriptor.getStartOffset ();
long end = descriptor.getLength ();
// get title
// songTitle=songsList.get(songIndex).get("songTitle");
// set the data source
try
{
m.setDataSource ( descriptor.getFileDescriptor (), start, end );
}
catch ( Exception e )
{
Log.e ( "MUSIC SERVICE", "Error setting data source", e );
}
m.prepare ();
m.setVolume ( 1f, 1f );
// m.setLooping(true);
m.start ();
}
catch ( Exception e )
{
e.printStackTrace ();
}
}
this works for me:
public static class eSound_Def
{
private static Android.Media.MediaPlayer mpBeep;
public static void InitSounds( Android.Content.Res.AssetManager Assets )
{
mpBeep = new Android.Media.MediaPlayer();
InitSound_Beep( Assets );
}
private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
{
Android.Content.Res.AssetFileDescriptor AFD;
AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
AFD.Close();
mpBeep.Prepare();
mpBeep.SetVolume( 1f, 1f );
mpBeep.Looping = false;
}
public static void PlaySound_Beep()
{
if (mpBeep.IsPlaying == true)
{
mpBeep.Stop();
mpBeep.Reset();
InitSound_Beep();
}
mpBeep.Start();
}
}
In main activity, on create:
protected override void OnCreate( Bundle savedInstanceState )
{
base.OnCreate( savedInstanceState );
SetContentView( Resource.Layout.lmain_activity );
...
eSound_Def.InitSounds( Assets );
...
}
how to use in code (on button click):
private void bButton_Click( object sender, EventArgs e )
{
eSound_Def.PlaySound_Beep();
}

Categories

Resources