android – Firebase , how to play an audio in firebase storage when clicking a button?

Question:

I am developing an application , which when I click a button it plays an audio , but if I put all the audios in the application , it will be very heavy , I would be able to put these audios in firebase , and make when I click the button it plays using firebase server ? Thanks !

Answer:

First, you need to know how you are handling these Áudio files.

As you mentioned, 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-created audios

Fortunately Firebase allows us to send files to Storage manually, doing this:

  • Access the Firebase dashboard
  • Go to Storage and click on upload file

You will be able to send files like: Image , Audio , Video and so on… And they were stored in Google Cloud Storage .

Once you've uploaded it, you'll be able to download it by code, but before we get to the part we need to do a few things first.

Firebase , by default, will not allow unauthenticated users to access these files, this means that only users logged in with Firebase Auth will be able to download and upload 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 be able to download the files.

To start modifying Firebase Storage rules, you can start here . He gives us an example of what 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 the store . To allow unauthenticated users to upload 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#EditRules

Okay, following the steps above, we will be able to download your audio files and play them by stream, which is the part that interests us.

What you need to know is: we won't be downloading the file to local storage, we can run the file directly via StreamUrl . We'll make a request to Firebase to return the Stream Url of the audio file, then we'll send it to 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 play audio remotely using Firebase Storage. If you want to go deeper, such as downloading files and storing them on the device, you will need this:Firebase#DownloadFiles

Scroll to Top
AllEscort