How do I play an mp3 in the res/raw folder of my android app?

后端 未结 3 638
时光取名叫无心
时光取名叫无心 2020-11-28 11:51

I have a small (200kb) mp3 in the res/raw folder of my android app. I am trying to run it in an emulator from Eclipse. It is recognized as a resource in the R file but when

3条回答
  •  自闭症患者
    2020-11-28 12:19

    this is a static method I use in my projects. I add it to my Utils class:

        public static void playSound(final Context context, final SoundType type)
        {
    
                new Thread(new Runnable()
                {
    
                    @Override
                    public void run()
                    {
                        MediaPlayer mediaPlayer = new MediaPlayer();
                        int resId = -1;
                        switch (type)
                        {
                        case INCOMING_NOTIFICATION:
                            resId=R.raw.noti_sound;
                            break;
                        case SEND_BETTING_SLIP:
                            resId=R.raw.slip_sent;
                            break;
                        case TRIVIA_RIGHT_ANSWER:
                            resId=R.raw.game_bonus;
                            break;
                        case TRIVIA_WRONG_ANSWER:
                            resId=R.raw.whistle_referee_trivia_bad_answer;
                            break;
                        }
    
                        if (resId != -1)
                        {
                            mediaPlayer = MediaPlayer.create(context, resId);
                            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            mediaPlayer.setLooping(false);
                            mediaPlayer.start();
    
                            while (mediaPlayer.isPlaying() == true)
                            {
                            }
                        }
                    }
                }).start();
    
            }
    }
    

    now I defind an Enum (SoundType) and placed the mp3 files in raw folder under res folder.

提交回复
热议问题