Home > Java > body text

How to make audio stop when another audio starts (lots of audio)

PHPz
Release: 2024-02-12 14:06:05
forward
574 people have browsed it

Question content

I have 30-31 buttons and I want them to play one at a time, so if I click one button it plays, then when I click another button whatever Whichever button it is, it will stop, here is the code sample basically does that and repeats, but just the numbers change, so 1,2,3,4 etc:

public void Button1Text(View view) {
        Media1 = MediaPlayer.create(QuranJ30MA.this, R.raw.hannaba);
        Media1.start();
    }

    public void Button1Text2(View view) {
        Button1p = MediaPlayer.create(QuranJ30MA.this, R.raw.mannaba);
        Button1p.start();
    }
Copy after login

I did try to see if other people are trying to do the same thing but since I'm not very good with java I don't understand how to apply it to my machine, if it's not too much to ask I just want to explain Let's learn how it works, thanks :)

Solution

You should never create multiple mediaplayers, they are heavyweight objects and take up a lot of resources. Instead, make a media player and use setdatasource to change the sound its settings play (of course, you'll need to stop the original sound first).

The next thing to change is the build data. Create a mapping of ids to sounds:

map<int, int> sounds = new hashmap();
sounds.put(button1id, r.raw.hannaba);
sounds.put(button2id, r.raw.mannaba);
...
Copy after login

Then you can have the click function:

public void buttonClick(View view) {
   mediaPlayer.stop()
   mediaPlayer.setDataSource(sounds.get(view.getId())
   mediaPlayer.start()
}
Copy after login

Set this as the onclicklistener for all buttons you want to execute and only need to write it once.

The above is the detailed content of How to make audio stop when another audio starts (lots of audio). For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template