Firebase , how to play an audio in the firebase Audio Log by clicking a button?

Asked

Viewed 858 times

2

I’m developing an application , that when clicking a button it plays an audio , but if I put all the audios in the application , will be very heavy , would have as I put in firebase these audios , and make sure that by clicking the button it plays using the firebase server ? Thank you !

  • What language do you use?

1 answer

1

First, you need to know how you are dealing with these Áudio.

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

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

  • Access the Firebase dashboard
  • Go to Storage and click Upload File

You can send files as: Imagery, Audio, Video and so on... and they were stored in Google Cloud Storage.

After uploading, you can already download by code, but before we go to the part that matters it is necessary to do a few things before.

The Firebase, by default, will not allow unauthenticated users to access these files, it means that only user connected with the Firebase Auth may download and upload files, but of course, this is not required, you can configure these rules in the dashboard itself. This, of course, if you want unauthenticated users to be able to download the files.

To start modifying the rules of Firebase Storage, you can start by here. It gives us an example of how rules can be:

service firebase.storage {
  match /b/<your-firbase-storage-bucket>/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

That rule means that only authenticated users can read and send files to storage. To allow non-authenticated users to send and read files, let’s:

service firebase.storage {
  match /b/<your-firbase-storage-bucket>/o {
    match /{allPaths=**} {
      allow read, write
    }
  }
}

To edit your rules, see this: Firebase#Editarregras

Okay, following the above steps, 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 the local storage, we can run the file directly by Streamurl. We will make a request that the Firebase return to Url of Stream of the audio file, done this, we will send to the Media Player 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 audio remotely using Firebase Storage. If you want to go deeper, such as downloading files and storing them on your device, you will need this: Firebase#Downloadfiles

  • Luc , ta dar erro nessa linha mediaPlayer.setOnPreparedListener(this);

  • no log aparece assim error: incompatible types: Mainactivity cannot be converted to Onpreparedlistener

  • I edited the answer

  • but , how the app will know that I’m picking up from my firebase? where I set up to search directly in my Storage?

  • When you configure Android Studio with Firebase, it is already connected to your Firebase.

  • Unless you haven’t set it up, of course. Just edit that line: firebaseStorage.getReferenceFromUrl("audios/my_file_cool_audio");

  • It points to your database, and of course, you must put the right file path(s)

  • Here did not work no , the app closes , but I will give a search , thanks for the help

  • I don’t know how you set up the app with firebase, by android studio da para fazer automaticamente. This was more of a guide, I recommend you look at the answer links!

  • I just called the account only , blz worth

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.