Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize Audio playback in Android Development

Shulou Source: shulou.com Published: 2022-05-31 13:31:21 09月12日 Update

This article mainly explains "how to achieve audio playback in Android development", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to play audio in Android development.

Add another play (Sound) method to BeatBox:

Play audio (BeatBox.java)

MSoundPool = new SoundPool (MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0)

LoadSounds ()

}

Public void play (Sound sound) {

Integer soundId = sound.getSoundId ()

If (soundId = = null) {

Return

}

MSoundPool.play (soundId, 1.0f, 1.0f, 1,0,1.0f)

}

Public List getSounds () {

Return mSounds

}

Check to make sure that soundId is not a null value before playing. Failure to load Sound results in a null value for soundId.

After the check passes, you can call the SoundPool.play (int, float, float, int, int, float) method to play the audio. These parameters are: audio ID, left volume, right volume, priority (invalid), whether to loop, and playback rate. We need maximum volume and constant speed to play, so input a value of 1.0. Whether the loop parameter is passed a value of 0, which means there is no loop.

Finally, add a button listener method to click the button to play audio, as shown below:

Click the button to play audio (BeatBoxFragment.java)

Private class SoundHolder extends RecyclerView.ViewHolder

Implements View.OnClickListener {

Private Button mButton

Private Sound mSound

Public SoundHolder (LayoutInflater inflater, ViewGroup container) {

Super (inflater.inflate (R.layout.list_item_sound, parent, false))

MButton = (Button) itemView.findViewById (R.id.list_item_sound_button)

MButton.setOnClickListener (this)

}

Public void bindSound (Sound sound) {

MSound = sound

MButton.setText (mSound.getName ())

}

@ Override

Public void onClick (View v) {

MBeatBox.play (mSound)

}

}

Run the application again, click any button, and you should be able to hear the audio playing, as shown in the following figure.

At this point, I believe you have a deeper understanding of "how to achieve audio playback in Android development". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Audio methods buttons development volume loops content parameters learning checking practical deeper maximum representative priority interest again practical practical easy to operate Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Xiaomi OPPO Reno Huawei Redmi