streaming a mp3 from a site/server - android

hi guys me and a few other djs want to be able to upload our mixes to a site that could then be streamed direct in to my app. at the moment i have the files stored on google drive. they will download and then i can play via a media player. but i want the user to be able to just stream the music direct from the site..
1) what site would you suggest for uploading of the music. i have a firebase account would this be an idea or would the data from the files i upload be expensive? im on the pay as you go account type.
****EDIT
So ive found out that firebase could be a n actual viable option for doing this
2) what would be the best way to implement the code so that it streams the music direct rather than downloading it first?
****EDIT
ive found some code while trawling the internet that could make this viable but i seam to be getting a null pointer error on the setDatasource
this is my code
i have this my onchild added
final String url = dataSnapshot.child("url").getValue(String.class);
urlList.add(url);
then in my onitemclick i use
mp3url = urlList.get(i);
fetchAudioUrlFromFirebase();
finally the method for streaming the mp3
private void fetchAudioUrlFromFirebase() {
String mp3 = mp3url;
final FirebaseStorage storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl(mp3);
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
// Download url of file
final String url = uri.toString();
mMediaplayer.setDataSource(url);
// wait for media player to get prepare
mMediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mMediaplayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("TAG", e.getMessage());
}
});
}
this is my full logcat with the null pointer error
07-11 18:39:45.326 2565-2565/com.example.harrops.h20droidapp2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.harrops.h20droidapp2, PID: 2565
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:198)
at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:192)
at com.google.android.gms.tasks.zze$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Following line means: mMediaPlayer is null.
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.media.MediaPlayer.setDataSource(java.lang.String)'
on a null object reference
Please check mMediaplayer is initialized before onSuccess(Uri uri) method is called.
mMediaplayer = new MediaPlayer();

Q1: i have no idea about a site do this, sorry
Q2: you have to learn how to use MediaPlayer class in android and here is an example :
String link = "your link.mp3"; //usually it's ends with .mp3
Mediaplayer player = new MediaPlayer();
player.setDataSource(link);
player.prepare();//prepare to play
player.start();
Its a quick and very simple example.
You can edit this as your need.

Related

Playing audio file from Firebase storage in android MediaPlayer

I'm trying to play audio file from Firebase storage in my application.
I wrote code exactly same from the youtube video about this, but it doesn't play a song.
Can anybody tell what is the problem?
I tried pretty many solutions in some questions
such as missing permission in Manifest, relocation of MediaPlayer methods etc.
Nothing worked.
public void play_Song(View view) {
final MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource( url );
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
} );
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
}
} );
}
When I run play_Song method, I can check following
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService#aeb6194): Cookies: null
V/MediaHTTPService: makeHTTPConnection: CookieManager created: java.net.CookieManager#a6bd43d
makeHTTPConnection(android.media.MediaHTTPService#aeb6194): cookieHandler: java.net.CookieManager#a6bd43d Cookies: null
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
and after a while, I can check this out
E/MediaPlayerNative: error (1, -2147483648)
W/System.err: java.io.IOException: Prepare failed.: status=0x1
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1274)
at techtown.testtest.mediaplayertest.MainActivity.play_Song(MainActivity.java:71)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
W/System.err: at android.view.View$PerformClick.run(View.java:27336)
W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/catch: complete
I/Choreographer: Skipped 1813 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=30227ms; Flags=0, IntendedVsync=531877218816690, Vsync=531907435482148, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=531907438049220, AnimationStart=531907438097820, PerformTraversalsStart=531907438477920, DrawStart=531907438622820, SyncQueued=531907439252120, SyncStart=531907440144220, IssueDrawCommandsStart=531907440191720, SwapBuffers=531907441436520, FrameCompleted=531907447223120, DequeueBufferDuration=468000, QueueBufferDuration=353000,
You can use this for NetworkSecurityConfig error:
android:usesCleartextTraffic="true"
add to application in manifest file.
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaplayer.prepareAsync();
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
I tried with audio from Firebase Storage and it works
I have had this issue in the past with many things regarding Firebase. You should make sure get your permissions/security rules in Firebase are correct. You may have to wait a few minutes before the rules are set, and then you may be able to read;write your files.
You can find your rules when clicking on "Storage" from the menu, and then clicking on "rules" tab. You should see "files", "rules", and "usage".
When first starting out, I usually make sure my rules read as follows:
rules_version = '2';
// Anyone can read or write to the bucket, even non-users of your app.
// Because it is shared with Google App Engine, this will also make
// files uploaded via GAE public.
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}

I can't play some audio got from firebase storage

I'm trying to get audios from firebase storage and play with MediaPlayer. And actually I can do this but the problem is I can't play some of the audios. I realized that it can't play audios which have size higher than 50 kb. I can play audios which the size less than 50 kb.
Btw this is my first question here. Sorry for mistakes.
Errors:
E/FLACExtractor: unsupported sample rate 44000
E/GenericSource: initFromDataSource, source has no track!
E/GenericSource: Failed to init from data source!
E/MediaPlayerNative: error (1, -2147483648)
E/MediaPlayer: Error (1,-2147483648)
public class KelimeSecimActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
MediaPlayer mMediaplayer = new MediaPlayer();
private Button buttonBasla ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kelime_secim);
buttonBasla = findViewById(R.id.buttonBasla);
mMediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
fetchAudioUrlFromFirebase();
buttonBasla.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPrepared(mMediaplayer);
}
});
}
private void fetchAudioUrlFromFirebase() {
final FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("MY_URL");
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
// Download url of file
final String url = uri.toString();
mMediaplayer.setDataSource(url);
// wait for media player to get prepare
mMediaplayer.setOnPreparedListener(null);
mMediaplayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
As i said, there is no problem if the audio size low than 50 kb. Actually i'm not sure whether it's because of size. But I tried many files and result is like this.
I am able to reproduce the issue. The files you mentioned do work in other players, but don't work in Android's MediaPlayer.
The problem files are all encoded at 44000Hz, using libFLAC 1.1.3.
The files that work are all 44100Hz, using libFLAC 1.1.2.
The size correlation appears to be a coincidence. For instance, En-us-you_re2.flac plays fine. It's 166KB, but it's 44100Hz.
It's clear that 44000Hz is a valid rate, but MediaPlayer simply doesn't support it. You may have better luck with exoplayer with the FLAC extension. Worst case, you might have to find your own decompression library and do the conversion yourself.

Android MediaPlayer prepare failed: status = 0x1 and Mediaplayer.creat() returns null with .AAC audio file

I am accessing the audio files from
/data/user/0/app_packagename/files/filename
I don't have WRITE_EXTERNAL READ_EXTERNAL permissions.
Now I can access files which are saved in the /data/user/0/app_packagename/files/ without WRITE_EXTERNAL READ_EXTERNAL permissions.
And can able to play all the audio files in my application.
In my application I am playing all files in queue. Few of my users are not able to play second audio file once 1st audio file completed.
Below is my code
void playNext(File varientFile) {
if (mSessionMediaPlayer != null) {
if (mSessionMediaPlayer.isPlaying()) {
mSessionMediaPlayer.stop();
}
mSessionMediaPlayer.release();
mSessionMediaPlayer = null;
}
mSessionMediaPlayer = new MediaPlayer();
if (mSessionMediaPlayer != null) {
Uri uri = Uri.parse(variantFile.getAbsolutePath());
mSessionMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mSessionMediaPlayer.setDataSource(this, uri);
mSessionMediaPlayer.setLooping(false);
mSessionMediaPlayer.prepare();
mSessionMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
playNext(mFiles.get(mNextIndex);
}
});
mSessionMediaPlayer.start();
runScheduler();
}
}
Instead of
mSessionMediaPlayer = new MediaPlayer();
I had tried with
mSessionMediaPlayer = MediaPlayer.create(getApplicationContext(),
uri);
Even MediaPlayer.create() is returning null. mSessionMediaPlayer.prepare() is throwing an exception
Cause : Prepare failed.: status=0x1
Whats wrong with my code? Why it is getting null or prepare failed? I had tested the files as well they are working, audio file format is in .aac.
The same user who is not able to play second audio file. He is able to play first file with the same code. But if same method is calling from onCompleted() it is not working. Why so?
Can anyone please help me to fix this issue?
Instead of creating a new object every time, try with the same Media Player object something like this.
MediaPlayer mSessionMediaPlayer;
mSessionMediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mSessionMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mSessionMediaPlayer) {
moveToNext(mSessionMediaPlayer,nextUri);
}
});
mSessionMediaPlayer.prepare();
mSessionMediaPlayer.start();
private void moveToNext(MediaPlayer mSessionMediaPlayer,Uri uri){
mSessionMediaPlayer.create(getApplicationContext(), uri);
mSessionMediaPlayer.prepare();
mSessionMediaPlayer.start();
}

Android mediaplayer using uri causes app crash

I have been working to resolve this problem for the last three days and cannot get it working. These are the steps of my app:
Open file browser to select and audio file
Audio file is selected
Selected audio file is added to the database
from a list of items the added file is selected
a play button is pressed to play the sound file
at this point the sound file will play, however if I close the app then open it again and attempt to play the same sound file the app crashes with the following error:
FATAL EXCEPTION: main
Process: com.arcitech.developer.ultimatesoundboard, PID: 22967
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.arcitech.developer.ultimatesoundboard.activities.ItemDetailFragment$4.onClick(ItemDetailFragment.java:153)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
the filepath(uri) I am saving to the database is:
Content://com.android.providers.media.documents/document/audio%3A15790
and the code I am using is located in the onCreateView of a fragment:
MediaPlayer m;
playSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (m != null) {
m.stop();
m.release();
m = null;
}
m = MediaPlayer.create(getActivity(), Uri.parse(mItem.filePath));
m.start();
m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer m) {
countdownTimerHandler.removeCallbacks(countdownTimerRunnable);
}
});
}
});
According to the doc for MediaPlayer.create(), it can return null if for some reason MediaPlayer cannot be created. You should be checking the return value for null every time unless you are very confident that it will not return null (but even then, do it for safety).
You may also want to check the log at the time create() is called to see if Android is leaving any clues as to why creation failed.

Play Mp4 video from server android

I want to play video of mp4 format and size 4-5Mb from server in streaming mode.I am using sdk version 2.3,on emulator it
gives only sound but not any picture.
I also tested it on devices Samsung(android sdk ver 2.1) and LG optimus(android sdk ver 2.2)
and only get "cannot play video:sorry this video is not valid for streaming to this device" message.
I have searched on this but not getting any solution, if anybody have any solution please help me.Thanks in advance.
Here is my code:
public class ShowVideo extends Activity
{
private static ProgressDialog progressDialog;
public String video_url;
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.videoalbum);
progressDialog = ProgressDialog.show(ShowVideo.this, "", "Buffering video...", true);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
video_url = "http://www.letumobi.com/videouploads/cd0a4170-1fb2-4fba-b17c-b5d70b2cd2e7.mp4";
try {
final VideoView videoView =(VideoView)findViewById(R.id.video_viewId);
mediaController = new MediaController(ShowVideo.this);
mediaController.setAnchorView(videoView);
// Set video link (mp4 format )
Uri video = Uri.parse(video_url);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
videoView.start();
}
});
}catch(Exception e){
progressDialog.dismiss();
System.out.println("Video Play Error :"+e.getMessage());
}
}
You may try these urls (ends with .3gp):
http://daily3gp.com/vids/747.3gp
http://daily3gp/www/vids/juggling_while_on_unicycle.3gp
instead of .mp4 urls:
video_url = "http://www.letumobi.com/videouploads/cd0a4170-1fb2-4fba-b17c-b5d70b2cd2e7.mp4";
On emulator it is difficult to get video played, because it needs really fast computer. Try this link for emulator. Maybe you can get some discrete video view.
http://commonsware.com/misc/test2.3gp
Also in your real devices this link should work if your implementation is proper.
I assume your video using following link
"http://www.letumobi.com/videouploads/cd0a4170-1fb2-4fba-b17c-b5d70b2cd2e7.mp4
is not proper for safe streaming.
You should hint that video or play other hinted videos. I couldn't find any other solution for playing unhinted videos yet.
This link may help.
getting PVMFErrContentInvalidForProgressivePlayback error while playing mp4 files on samsung devices

Categories

Resources