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
Related
here is string to setDataSource
/data/data/com.player/app_player/file.mp3
getting E/Exception: setDataSource failed.
here is the code:
mediaPlayer.setDataSource(context, Uri.parse("/data/data/com.player/app_player/file.mp3"));
I stored that file using this code
getContext().getDir("player", Context.MODE_PRIVATE)
which is same as /data/data/com.player/app_player
using content://data/data/com.player/app_player/file.mp3 did not work.
This is how I solve it.
String musicUrl = "";
if (songSavedInDB()) {
musicUrl = "here is any file path(Internal or external)"
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(musicUrl);
mPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mPlayer.prepare();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
musicUrl = "here is url";
try {
mPlayer.setDataSource(getContext(), Uri.parse(musicUrl));
mPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
I had start download file and start playing that file. If the file size is small (less than 15 MB). Following source download and play video perfectly.
If the file size is big (50 MB or more than that),Video playing getting started. For my case,File size is 50 MB,downloaded size is 10 MB and video view is played when the download is started, once the 10 MB size video is played,It waiting for the upcoming bytes. When it gets downloaded, audio only get played. Video frame is not get updated.
public class VideoDemo extends Activity {
private MediaController ctlr;
VideoView videoView = null;
Context context = null;
long totalRead = 0;
int bytesToRead = 50 * 1024;
private int mPlayerPosition;
private File mBufferFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
videoView = (VideoView) findViewById(R.id.videoview);
ctlr = new MediaController(this);
ctlr.setMediaPlayer(videoView);
videoView.setMediaController(ctlr);
videoView.requestFocus();
new GetYoutubeFile().start();
}
private class GetYoutubeFile extends Thread {
private String mUrl;
private String mFile;
public GetYoutubeFile() {
}
#Override
public void run() {
super.run();
try {
File bufferingDir = new File(
Environment.getExternalStorageDirectory()
+ "/YoutubeBuff");
InputStream stream = getAssets().open("famous.3gp");
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("test", "mp4");
System.out.println("hi");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
File bufferFile = File.createTempFile("test", "mp4");
BufferedOutputStream bufferOS = new BufferedOutputStream(
new FileOutputStream(bufferFile));
InputStream is = getAssets().open("famous.3gp");
BufferedInputStream bis = new BufferedInputStream(is, 2048);
byte[] buffer = new byte[16384];
int numRead;
boolean started = false;
while ((numRead = bis.read(buffer)) != -1) {
bufferOS.write(buffer, 0, numRead);
bufferOS.flush();
totalRead += numRead;
if (totalRead > 120000 && !started) {
Log.e("Player", "BufferHIT:StartPlay");
setSourceAndStartPlay(bufferFile);
started = true;
}
}
mBufferFile = bufferFile;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setSourceAndStartPlay(File bufferFile) {
try {
mPlayerPosition=videoView.getCurrentPosition();
videoView.setVideoPath(bufferFile.getAbsolutePath());
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onCompletion(MediaPlayer mp) {
mPlayerPosition = mp.getCurrentPosition();
try {
mp.reset();
videoView.setVideoPath(new File("mnt/sdcard/YoutubeBuff/"
+ mBufferFile).getAbsolutePath());
mp.seekTo(mPlayerPosition);
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Karthick
Your code seems ok!!
just register the OnCompletionListener,OnErrorListener to your VideoView.
videoView.setOnCompletionListener(this);
videoView.setOnErrorListener(this);
so once media player played the buffered stream it will goes to onCompletion or throws an error(Video Can't be played), Which can be handle by again changing seek position and playing through same buffered file.
(Please make sure that video bitrate and transfer rate needs to be equivalent) so buffering and streaming will run simultaneously.
implementations of methods could be like below,
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mPlayerErrorPos = mp.getCurrentPosition();
mPlayerPosition=mPlayerCompletionPos > mPlayerErrorPos ? mPlayerCompletionPos : mPlayerErrorPos;
try {
mp.reset();
videoView.setVideoPath(video.getAbsolutePath());
videoView.seekTo(mPlayerPosition);
videoView.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayerCompletionPos = mp.getCurrentPosition();
}
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 ..
I'm sure that this question has been asked before but I've been unable to find a solid answer. I'm trying to load a streaming audio from a server. Its a audio/aac file
http://3363.live.streamtheworld.com:80/CHUMFMAACCMP3
The code that I'm using is
private void playAudio(String str) {
try {
final String path = str;
if (path == null || path.length() == 0) {
Toast.makeText(RadioPlayer.this, "File URL/path is empty",
Toast.LENGTH_LONG).show();
} else {
// If the path has not changed, just start the media player
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
mp.setDataSource(getDataSource(path));
mp.prepareAsync();
mp.start();
}catch(IOException e){
Log.i("ONCREATE IOEXCEPTION", e.getMessage());
}catch(Exception e){
Log.i("ONCREATE EXCEPTION", e.getMessage());
}
}
} catch (Exception e) {
Log.e("RPLAYER EXCEPTION", "error: " + e.getMessage(), e);
}
}
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("RPLAYER IOEXCEPTION", "error: " + ex.getMessage(), ex);
}
return tempPath;
}
}
Is this the correct implementation? I'm not sure where I'm going wrong. Can someone please please help me on this.
The method prepareAsync() is asynchronous -- quoting the documentation:
Prepares the player for playback, asynchronously.
You need to call setOnPreparedListener(), supplying a MediaPlayer.OnPreparedListener. Then, in that listener's onPrepared(), you can call start().
AAC streaming format is not supported and you cannot directly play Shoutcast stream in Android version less than 2.2..
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.