简体   繁体   中英

android play multiple sounds

In my android app the user may click on different views to produce piano sounds. My sounds are stored in the raw folder (do_note.mp3,re_note.mp3,...)

My problem is when the user click on a view, a sound is produced but after 6 or 7 clicks the sounds stops and there is no more after. here is my function code :

public int playSound(String tag){



            id = context.getResources().getIdentifier(tag, "raw", context.getPackageName());


            int soundId = sp.load(context, id,1);

            MediaPlayer mPlayer = MediaPlayer.create(context,id);

            mPlayer.start();



        }

Always check if mPlayer already stopped

        @Override
        public void onClick(View v) {

            if(mPlayer.isPlaying())
            {  
                mPlayer.stop();
                mPlayer.reset();
            } 
            try {

                AssetFileDescriptor afd;
                afd = getAssets().openFd("your.sound");
                mPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                mPlayer.prepare();
                mPlayer.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });

You can change onClick() method and put code to your function

Hope this helps you

Thank's JakSok

your answer guide me to find solution, in fact i have to call reset and release methods for my MediaPlayer, this is my solution :

 if(mPlayer.isPlaying()) {
        mPlayer.stop();
    }

        int id = getResources().getIdentifier(fileName, "raw", getPackageName());
        mPlayer.reset();
        mPlayer.release();
        mPlayer = MediaPlayer.create(this,id);
        mPlayer.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM