android Media Player E/MediaPlayer: Error (1,-1015) - android

i have shared a valid mp3 file in my google drive however I am not able to play it due to
E/MediaPlayer: Error (1,-1015)
I cannot find any documentation for this error
my link :"https://drive.google.com/file/d/1m_TKhtlPRBzBEencnU5-RITxheXm4x6q/view?usp=sharing"
my music service:
enter code here
package com.example.mpservice;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class PlayService extends Service implements
MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener
,MediaPlayer.OnSeekCompleteListener,MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnErrorListener {
MediaPlayer mediaPlayer;
public final String TAG="MyService";
#Override
public void onCreate() {
Log.d(TAG,"playService start");
mediaPlayer=new MediaPlayer();
//mediaPlayer=MediaPlayer.create(this,R.raw.summer);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
super.onCreate();
Log.d(TAG,"onCreate Finish");
}
#Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d(TAG, "onStartCommand");
String url = intent.getStringExtra("URL");
Log.d(TAG, "URL :" + url);
// Uri myUri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.summer);
// Uri myUri = Uri.parse(url);
//Log.d(TAG ,"URI: " +myUri);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
Log.d(TAG, "data source" + e);
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.d(TAG,"prepare :" + e);
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if(( mediaPlayer !=null)&& mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
Log.d(TAG, "media player stoped " );
}
Log.d(TAG, "on Destroy " );
Log.d(TAG, "media lpayer :"+mediaPlayer );
super.onDestroy();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "error media player " + what +extra);
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "info media player " + what +extra);
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "mp start ");
mp.start();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}

Related

All possible reasons that can stop mediaplayer

I have some problems with my Mediaplayer. It works well, but at some mysterious circumstances it stops playing. So i put some logs in onCompletion and onError callbacks and surround it with try/catch, but when it stops none of thees logs are triggering. So my question is how can Mediaplayer stops playing and dont trigger this logs.
P.S. it plays in service, but i checked - service continue running, and also i tried to play it in singleton class and GCMService too - it still stops and i can't figure out why.
Here is my code.
public class AlertService extends Service {
private boolean isPlaying = false;
private MediaPlayer mp;
private final String TAG = "Alert_playing";
public static final String PLAY_ALERT_ACTION = "play_alert_service";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent!=null&&intent.getAction().equals(PLAY_ALERT_ACTION)){
playAlertSound();
}
return START_NOT_STICKY;
}
public void playAlertSound() {
if (!isPlaying) {
isPlaying = true;
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
mp = new MediaPlayer();
Uri ringtone = Uri.parse("android.resource://" + RetailerApplication.getAppContext().getPackageName() + "/" + R.raw.alert);
try {
mp.setDataSource(RetailerApplication.getAppContext(), ringtone);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
}
});
}
});
mp.prepareAsync();
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
isPlaying = false;
stopSelf();
Log.d(TAG, "what: " + what + " extra: " + extra);
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
return false;
}
});
} catch (IOException e) {
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
Log.d(TAG, "exception" + e);
Logger.e(TAG, e);
}
} else {
Log.d(TAG, "miss");
}
}
}

Android streaming .wav audio file from server is not working

I have been trying to stream .wav file from server in the background. It works fine with .mp3 audio files. But when I try to play an .wav file, it is not playing. I implemented the audio player as a service. The following is the code
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class SoundService extends Service implements MediaPlayer.OnPreparedListener {
private static final String TAG = "MyService";
String url;
MediaPlayer mp;
public IBinder onBind(Intent intent) {
Log.i("OnBind", "Inside OnBind");
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate");
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d("Stopping", "onDestroy");
mp.stop();
}
#Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("Starting", "onStart");
url = intent.getExtras().getString("url");
Log.i("Starting2", "onStart2");
try {
mp.reset();
Log.i("URLIS",""+url);
mp.setDataSource(url);
Log.i("Datasource", "datasource");
mp.setOnPreparedListener(this);
Log.i("preparedlistener", "PreparedListener");
mp.prepareAsync();
Log.i("prepareasync", "prepareAsync");
} catch(Exception e){}
return START_STICKY;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.i("onprepared", "insideprepared");
mediaPlayer.start();
}
}
The service is called from the onactivityresult in mainActivity passing the url of audio file in intent.
public void onResponse(String response) {
Log.i("Myresponse",""+response);
Intent i = new Intent(MainActivity.this, SoundService.class);
i.putExtra("url",response);
startService(i);
Log.i("Myresponse",""+response);
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
}
My log cat when streaming .wav file is as follows
10-02 15:00:03.527 27677-27734/com.example.gkrish.momdadme E/MediaPlayer: error (1, -2147483648)
10-02 15:00:03.534 27677-27677/com.example.gkrish.momdadme E/MediaPlayer: Error (1,-2147483648)
The code u have written is correct and most probably because of the response

Mediaplayer current position is always zero

I am building a simple music app.
Regardless of what I try, I can not get a song to stop in order to play a new song. I tried stop, release, stop, and release together; I created a service; I even tried to use current position to get the position of the MP3 and consider it playing if the position is > 1.
But nothing worked and I am going mad trying to figure this out.
I worked on this for 5 days and have failed at everything I have thrown at it.
I would greatly appreciate any advice and a clear solution.
I am a noob and I am trying very hard to solve my own problems but this one just has me stumped.
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaplayer;
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String extRec = intent.getExtras().getString("extRec");
Log.d("My Service", "Received extra: " + extRec);
if (mediaplayer.isPlaying()){
Log.d("My Service is playing ", "yes");
}
else {
Log.d("My Service is playing ", "no");
}
//mediaplayer.stop();
//mediaplayer.release();
try {
final String AudioURL = extRec;
Log.d("My Service audioURL ", AudioURL);
mediaplayer.setDataSource(AudioURL);
mediaplayer.prepare();
Log.d("My Service", "position: " + mediaplayer.getCurrentPosition() );
mediaplayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return START_STICKY;
}
}
User Media Controller will help you:
public class AudioPlayer extends Activity implements OnPreparedListener, MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
//--MediaPlayerControl methods----------------------------------------------------
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
//--------------------------------------------------------------------------------
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}
For good playing feature use Exoplayer

Open video file from File Explorer and playing in my videoplayer activity

I have my VideoPlayerActivity.java and I want to open when I press on a video file from my sdcard through my file explore or another application
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;
public class VideoPlayerActivity extends Activity implements OnErrorListener, OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
MediaPlayerControl, SurfaceHolder.Callback, VideoControllerView.MediaPlayerControl, Runnable {
private static final String TAG = "Player";
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
VideoControllerView controller;
private int position;
private String videoPath;
int videoWidth, videoHeight;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video_player);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
videoPath = getIntent().getStringExtra("videoPath");
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
controller = new VideoControllerView(this);
try {
// String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
/* final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mediaPlayer != null) {
mediaPlayer.start();
return;
}
current = path;*/
// Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 166);
// Uri uri = MediaStore.Files.getContentUri("external");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.prepareAsync();
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
Intent intent = new Intent();
intent.setClass(VideoPlayerActivity.this, MainActivity.class);
startActivity(intent);
}
});
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoPath);
mediaPlayer.prepare();
Log.v(TAG, "Duration: ===>" + mediaPlayer.getDuration());
mediaPlayer.start();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
} /*catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}*/
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(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");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
private final Handler handler = new Handler (){
#Override
public void handleMessage(Message msg) {
final int currentPos = msg.getData().getInt("CurrentPosition");
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
/*if(controller.isShowing()) {
controller.hide();
}else {
controller.show();
}*/
return false;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
mediaPlayer.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
// End VideoMediaController.MediaPlayerControl
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
videoWidth = width;
videoHeight = height;
Toast.makeText(getApplicationContext(),
String.valueOf(videoWidth) + "x" + String.valueOf(videoHeight),
Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()){
surfaceHolder.setFixedSize(videoWidth, videoHeight);
}
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void run() {
// TODO Auto-generated method stub
controller = new VideoControllerView(this);
try {
mediaPlayer.setDataSource(videoSrc);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
/*
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("CurrentPosition", mediaPlayer.getCurrentPosition());
msg.setData(bundle);
handler.sendMessage(msg);
// handler.postDelayed(callBack, 500);*/
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
And my logcat error is
01-03 20:42:14.881: V/MediaPlayer(14737): setVideoSurfaceTexture
01-03 20:42:14.881: W/System.err(14737): java.lang.NullPointerException: uriString
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:468)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:458)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri.parse(Uri.java:430)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1256)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1221)
My XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:keepScreenOn="true"
android:id="#+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SurfaceView
android:id="#+id/playersurface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
And one more question. I have this public void method for streaming
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(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");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
How can I used to stream files from another application program?
When I play video from main activity it plays and when I quit and go to file explorer and chose my player from custom dialog box and open I have that problem with uriString...
When navigating through your files you can set a clicklistener on a thumbnail. I use this code to fire up a full-screen video editor:
thumbNail.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (pathType.equals("image")) {
<snip>
}
else {
// music file
}
else {
// must be video
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(cmsURL + pathListFull,"video/mp4");
PackageManager packageManager = getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivity(intent);
}
else {
Log.d("SHOWFILE", "no intents available");
}
}
}
});

How do I play a live HTTP audio stream in MediaPlayer on Android?

I want to play a live HTTP stream in my Android app, so I installed the Windows Media Encoder 9 on another PC on the same LAN, and used it to create a live HTTP audio stream.
The live HTTP stream is okay: I tested it, and it can be played by Windows Media Player or VLC on a PC, and can be played by VLC for Android on my mobile.
So, in my Android app, I wrote this code:
private MediaPlayer player = null;
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
//.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button)findViewById(R.id.play);
address = (TextView)findViewById(R.id.address);
btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
play();
}
});
}
private void play()
{
String serverIp;
serverIp = address.getText().toString(); // get the uri address, for example http://xxx.xxx.xxx.xxx:2340
if (player == null)
{
player = new MediaPlayer();
}
else
{
player.stop();
player.reset();
}
try {
Log.v("", "Init a new MediaPlayer");
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.v("", "Set the stream type to STREAM_MUSIC");
player.setDataSource(this, Uri.parse(serverIp));
Log.v("", "Set the source is " + serverIp);
player.setOnBufferingUpdateListener(this);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.prepareAsync();
Log.v("", "After prepareAsync");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.v("IllegalArgumentException", e.toString());
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.v("SecurityException", e.toString());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.v("IllegalStateException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("IOException", e.toString());
} catch (Exception e) {
Log.v("Exception",e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
Log.v("onPrepared", "After prepareAsync");
mp.start();
}
catch (Exception e) {
Log.v("play", e.toString());
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
Log.v("onBufferingUpdate", "Buffering Update");
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.v("MediaPlayer onError", "what=" + what + " extra=" + extra);
return true;
}
But it didn’t work. When I click the play button, nothing happens. But if I input some other URL I found on the internet (for example, http://www.example.com/song.mp3), it works.
So can anyone help me? The Log info is below. My mobile is HTC s710e, and my Android version is 4.0.4.
11-20 22:28:14.137: V/(580): Init a new MediaPlayer
11-20 22:28:14.137: V/(580): Set the stream type tp STREAM_MUSIC
11-20 22:28:14.147: D/MediaPlayer(580): Couldn't open file on client side, trying server side
11-20 22:28:14.178: E/Trace(39): error opening trace file: No such file or directory (2)
11-20 22:28:14.178: V/(580): After prepareAsync
11-20 22:28:14.297: V/ChromiumHTTPDataSource(39): connect on behalf of uid 10044
11-20 22:28:14.339: I/qtaguid(39): Tagging socket 27 with tag 3f500000000(1013) for uid 10044 failed errno=-2
11-20 22:28:14.629: I/ChromiumHTTPDataSourceSupport(39): Server responded with http status 400
11-20 22:28:14.648: I/qtaguid(39): Untagging socket 27 failed errno=-2
11-20 22:28:14.657: I/AwesomePlayer(39): mConnectingDataSource->connect() returned -1004
11-20 22:28:14.657: E/MediaPlayer(580): error (1, -1004)
11-20 22:28:14.667: E/MediaPlayer(580): Error (1,-1004)
11-20 22:28:14.667: V/MediaPlayer onError(580): what=1 extra=-1004
you can play HLS on android 3.0and 3.0 + version, older versions doesnt support HLS. This code below, can work on 3.0 + version. To play video all android version you have to use rtsp streaming or http prograssive download.
Player class
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class VideoPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private static final String MEDIA = "media";
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.VideoView);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
path = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
//mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(STREAM_VIDEO);
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
Main XML
<VideoView
android:id="#+id/VideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:layout_weight="1" android:background="#aaaaaa">
</LinearLayout>
</LinearLayout>
And you have to add to your manifest internet permission
uses-permission android:name="android.permission.INTERNET" />

Categories

Resources