Playing music from Parse.com android - java

so I'm implementing like music playlist app, my audios are uploaded to Parse.com as mp3 , I want to retrieve those audios ..
final Button btn = (Button) v.findViewById(R.id.button);
final ParseFile fileObject = object.getParseFile("music");
if (fileObject != null) {
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
final String audioFileURL = fileObject.getUrl();
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
}//end catch
catch (IOException e1) {
e1.printStackTrace();
}
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
this is how I retrieve music from Parse.com but this is taking so much time specially that I have a list of audios .. I want a way to download group of the audios in the background .. so when I click the button, the music play so fast .. any help would be greatly appreciated.

I have no time right now to understand why your code doesn't work, but you can take my sample app on github (committed just now), you should solve your problem...if not, let me know. Please, take note of the README.md
https://github.com/fullwipe/ParseAudioFileExample
Hope it helps...
Edit This is the essential part of my repository. Record and save:
String outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/rumor.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
Then, start recording...
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
When you stop recording, save it on Parse.com in this way:
FileInputStream fileInputStream = null;
File fileObj = new File(outputFile);
byte[] data = new byte[(int) fileObj.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(fileObj);
fileInputStream.read(data);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
ParseFile parseAudioFile = new ParseFile("audiofile.mp3", data);
parseAudioFile.saveInBackground();
ParseObject parseObject = new ParseObject("AudioFileClass");
parseObject.put("audiofile", parseAudioFile);
parseObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),"Audio file saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"Error: audio file not saved", Toast.LENGTH_SHORT).show();
}
}
});
Retrieve and play from Parse.com is very simple, I have used a ParseQueryAdapter. This is the part where you get the mp3 file and play it:
ParseFile descr = object.getParseFile("audiofile");
if (descr != null) {
String audioFileURL = descr.getUrl();
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(audioFileURL);
mediaPlayer.prepare();
mediaPlayer.start();
}
...
...

Related

How can I permanently save aufio files in Android?

I want to save .3gp files permanently in Android. I wrote methods for this but if I close the app and restart it, my app crashes when I try to play my recorded sound.
Here's my record-method(note that I have to code the path this way since API 29):
public void startRecording(){
try {
f = new File(getExternalFilesDir(null), "recorded.3gp");
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);;
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(f.getAbsolutePath());
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
My stop-method:
public void stopRecording(){
try {
mediaRecorder.stop();
mediaRecorder.release();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
My play-method:
public void playRecord(){
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(f.getAbsolutePath());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
In which folder can I find these recordings? I wanna get access later from app.
Thx

Prevent Android Studio Flutter app from closing after taking a picture

I am busy developing a APP On Android Studio using the Flutter framework, that functions as follows,
The user can press press a button and it will take a picture without opening the camera view.
I have a MethodChannel between my Dart/Flutter and Android.Java ,I am able to press the button and the app takes a pic and saves it to gallery.
The issue I am having is that it closes the app afterwards with no error.
Could you please have a look at my code and see if you can help me.
MainActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, Result result) {
if(call.method.equals("test"))
{
StartCameraFrontCamera();
}
else {
result.notImplemented();
}
}
});
}
public void StartCameraFrontCamera()
{
File directory = new File(Environment.getExternalStorageDirectory() + "/PicturesTest/");
if (!directory.exists()) {
directory.mkdir();
}
try {
ReleaseCamera();
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPictureFormat(ImageFormat.JPEG);
mCamera.setParameters(parameters);
SurfaceView mview = new SurfaceView(this);
SurfaceTexture surfaceTexture = new SurfaceTexture(0);
imageName = "fontcamera.jpg";
try{
//mCamera.setPreviewDisplay(mview.getHolder());
mCamera.setPreviewTexture(surfaceTexture);
//mCamera.setPreviewDisplay(null);
mCamera.startPreview();
mCamera.takePicture(null,null,photoCallback);
//mCamera.stopPreview();
}catch(IOException e) {
e.printStackTrace();
}
}
Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PicturesTest");
File file = new File (myDir, "image1.jpg");
FileOutputStream out = new FileOutputStream(file);
out.write(data);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
finish();
}
};

Playing .M3U links using Media Player

I need to play .M3U urls using Media Player, but it is not working:
Here is my code:
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http://xxxxxxxxx/1.m3u");
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
I have read all related question in this regards on stackoverflow but it is not help me,
Also I have tried to extract the .M3U by using this method:
public ArrayList<String> readURLs(String url) {
if (url == null) return null;
ArrayList<String> allURls = new ArrayList<String>();
try {
URL urls = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(urls
.openStream()));
String str;
while ((str = in.readLine()) != null) {
allURls.add(str);
}
Toast.makeText(this, allURls + "", Toast.LENGTH_SHORT).show();
Log.d("URL", String.valueOf(allURls));
in.close();
return allURls;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
But it was not working also when I call it
readURLs ("http://xxxxxxx.m3u");
So please help me.
Thanks in advance!
I would try to initialize the MediaPlayer differently:
MediaPlayer player = MediaPlayer.create(this, Uri.parse("http://xxxxxxxxx/1.m3u"));
Reference:
Why MediaPlayer throws NOT present error when creating instance of it?
Also don't forget to release the MediaPlayer once you are done with it.
player.release();
EDIT:
I explored the .m3u, but these contains other .m3u8playlists. I would recommend you to use Google's ExoPlayer instead which plays almost everything. https://github.com/google/ExoPlayer

Android File IO: Not saving/not loading the data

Background:
I am using three fragments and one activity in my application. Two fragments use recyclerViews and the other uses an expandableListView.
Problem:
I am trying to properly program the onPause(), onResume(), onStop(), and onRestart() methods to save the state of my application when the home, back, or switch views buttons are pressed.
To save the state of the program and load it when it comes back I have created the save() and load() methods in my one and only activity.
//from the end of onCreate
load();
}
#Override
protected void onStart() {
super.onStart();
mRef = new Firebase("https://sure-7856d.firebaseio.com/");
}
#Override
protected void onStop(){
super.onStop();
save();
}
#Override
protected void onPause(){
super.onPause();
save();
}
#Override
protected void onResume(){
super.onResume();
load();
}
#Override
protected void onRestart(){
super.onRestart();
load();
}
In the save method I get the adapters from my 2 recyclerViews and my expandableListView`s ArrayList that keeps track of which checkboxes are checked.
After that I put them each into a temporary Arraylist then I add each of those ArrayLists to a single arraylist that will be saved to the file.
private void save(){
//saved_data = new File("saved_data");
/*try {
if(saved_data.exists()==false){
//saved_data.createNewFile();
saved_data.setWritable(true);
}
} catch (IOException e) {
e.printStackTrace();
}*/
File myFile;
try{
myFile = new File(getFilesDir().getAbsolutePath(), "dir/save_data.bin");
myFile.mkdirs();
myFile.createNewFile();
FILENAME = myFile.getName();
}catch (IOException e){
e.printStackTrace();
}
OneFragment f20 = (OneFragment) frags.get(0);
TwoFragment f21 = (TwoFragment) frags.get(1);
ThreeFragment f22 = (ThreeFragment) frags.get(2);
ArrayList saveTasks = f20.adapter.getList();
ArrayList saveReqs = f21.adapter.getList();
ArrayList saveMap = new ArrayList<String>();
if(f22.listAdapter!=null) {
if (f22.listAdapter.getExport() != null) {
saveMap = f22.listAdapter.getExport();
}
}
ArrayList results = new ArrayList();
results.add(saveTasks);
results.add(saveReqs);
results.add(saveMap);
ObjectOutputStream oos1 = null;
FileOutputStream fos1 = null;
try {
fos1 = openFileOutput(FILENAME, Context.MODE_PRIVATE);
oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(results);
oos1.close();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos1 != null){
try {
oos1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the load code I get the object from the file and update the adapters to their previous state.
private void load(){
//saved_data = new File("saved_data");
ArrayList results = new ArrayList();
FileInputStream fis = null;
ObjectInputStream ois = null;
if(FILENAME==null){
return;
}
try {
fis = new FileInputStream(FILENAME);
ois = new ObjectInputStream(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
results = (ArrayList)(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof) try {
throw e;
} catch (OptionalDataException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for(int i = 0; i < results.size();i++){
if(i == 0){
frags.set(0,results.get(i));
}
else if(i == 1){
frags.set(1,results.get(i));
}
else if(i == 2){
frags.set(2,results.get(i));
}
else{
}
}
}
When I press the square button at the bottom of the emulator and go back to it one of a few things happen
It crashes saying the file could not be found
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
And this error points to the load method as the point of failure specifically
FileInputStream fis = null;
When I hit the triangle button nothing happens in logcat, everything is gone upon returning, and the app loses its functions of adding strings to lists on both recyclerViews and displaying both lists in the expandableListView.
Hitting the center circle button and going back to the app is fine nothing breaks.
Since Im getting a file not found error I think that the file isnt getting written
I have searched Stack for a solution and I am new to File IO and fragments, so I have no idea where to go from here.

Downloading list of audio from URL

So I'm implementing audio Playlist app that imports audios from Parse.com, and when I retrieve them by streaming them directly from their URls, it took maybe one minute to play after clicking play button.
So I don't want to use streaming from URL methods to play my audio from server because it makes it so slow. Instead I want to download list of audios from server (Parse.com) at once and then playing them by retrieving from sdcard.
I have the class that downloads single audio from single URL .. I want to edit the code to make it downloads more than one audio at once.
here is the class I have to download audio from URL.
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {
private Context mContext;
private MediaPlayer mPlayer;
public DownloadMusicfromInternet(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
// Output stream to write file in SD card
OutputStream output = new
Also if you could help me in how to set a name for the audios, I don't want to write static name because I'm downloading more than one audio at a time .
FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+"how to put unique name for each audio here ?"+".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Play the music
playMusic();
}
// Play Music
protected void playMusic() {
// Read Mp3 file present under SD card
Uri myUri1 = Uri.parse("file:///sdcard/"+"the same unique name that was set previously ! "+".mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(mContext.getApplicationContext(), myUri1);
mPlayer.prepare();
// Start playing the Music file
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// Once Music is completed playing, enable the button
// btnPlayMusic.setEnabled(true);
Toast.makeText(mContext.getApplicationContext(), "Music completed playing", Toast.LENGTH_LONG).show();
}
});
} catch (IllegalArgumentException e) {
Toast.makeText(mContext.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(mContext.getApplicationContext(), "URI cannot be accessed, permissed needed", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(mContext.getApplicationContext(), "Media Player is not in correct state", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(mContext.getApplicationContext(), "IO Error occured", Toast.LENGTH_LONG).show();
}
}
}
and this is my adapter, and here is where my problem occurs and crashes my app. I don't know how to call ( DownloadMusicfromInternet ) more than once from the following adapter .
public class mAdapter extends ParseQueryAdapter<ParseObject> {
public mAdapter (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MusicPlaylist");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.list_music, null);
}
super.getItemView(object, v, parent);
//Audio retrieving
final ImageButton btn = (ImageButton) v.findViewById(R.id.play_btn);
final ParseFile fileObject = object.getParseFile("music");
**// here I put a loop because I want it to download a list of audios at once and I think here is the problem**
if (fileObject != null) {
for (int i = 10; i >= j; j++) {
new DownloadMusicfromInternet().execute(fileObject.getUrl());
}
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
return v;
}//end getItem View
}//end mAdapter
Any help would be appreciated ..

Categories

Resources