First, you need to know how you're dealing with these Áudio
files.
As you have been quoted, it is not recommended to store very large files in the application, the question is: Do you have these pre-made audios or do you allow the user to create these audios?
I have pre-built audios
Fortunately Firebase allows us to send files to Storage manually, doing the following:
- Access the Firebase dashboard
- Go to Storage and click on Upload File
You can upload files like Image , Audio , Video , and so on ... And they were stored in Google Cloud Storage .
Once you've uploaded, you'll be able to download by code, but before we go to the part that interests you you need to do some things first.
Firebase will not allow non-authenticated users to access these files by default, which means that only users connected to Firebase Auth can download and send files, but of course, this is not mandatory, you can configure these rules in the panel itself. This, of course, if you want unauthenticated users to download the files.
To start modifying the Firebase Storage rules, you can start by here . It gives us an example of how the rules can be:
service firebase.storage {
match /b/<your-firbase-storage-bucket>/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
This rule means that only authenticated users will be able to read and send files to storage . To enable unauthenticated users to send and read the files, let's do:
service firebase.storage {
match /b/<your-firbase-storage-bucket>/o {
match /{allPaths=**} {
allow read, write
}
}
}
To edit your rules, see this: Firebase # Edit Rules
Done, followed the steps above, we can do the download of your audio files and run them by stream, which is the part that interests us.
What you need to know is: we will not download the file to local storage, we can run the file directly by StreamUrl .
We will request that Firebase return to the Stream url of the audio file, so we will send it to the Media Player to play the file .
public class AudioActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
private Button reproduceAudio;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_audio);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
reproduceAudio = (Button) findViewById(R.id.action_reproduce_audio);
reproduceAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Primeiro vamos intanciar o FirebaseStorage para que possamos receber os links dos arquivos
final FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
/* Agora podemos pegar a referência do nosso arquivo de áudio
podem ser múltiplos arquivos, para isso, consulte a documentação do firebase
O caminho do seu arquivo de áudio estará disponível no console */
StorageReference storageReference = firebaseStorage.getReferenceFromUrl("audios/my_file_cool_audio");
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
final String audioUrl = uri.toString();
// enviar como parâmetro para o método sendUrlToMediaPlayer()
sendUrlToMediaPlayer(audioUrl);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("Audio Error", e.getMessage());
}
});
}
});
}
void sendUrlToMediaPlayer(String url) {
try {
// enviar a StreamUrl para o player
mediaPlayer.setDataSource(url)
// esperar que ele fique pronto e após ficar pronto tocar o áudio
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IOException err) {
Log.e("Audio Error", err.toString());
}
}
}
This is basically what you need to run audios remotely using Firebase Storage. If you'd like to go deeper, such as downloading the files and storing them on your device, you'll need this: Firebase # DownloadFiles