2012-10-23 113 views
7

因此,在我的2.3設備上,即使設備音量設置爲0 /靜音,我也可以以全音量播放SoundPool或MediaPlayer的聲音。我的理解是,您必須手動獲取設備級別並在播放聲音時進行設置。不管設備音量如何,播放聲音

這就是我想要的行爲工作。

但是,現在我注意到我的4.0設備上,聲音是在設備的設置級別自動播放的,我不想要!

這是操作系統版本之間的區別嗎?如果是這樣,有沒有辦法忽略設備的音量?所以即使它靜音了,我也可以發出聲音並聽到它?

我不能進入爲什麼我需要這個功能,但我真的很喜歡。

謝謝!

+0

我覺得你真的應該解釋爲什麼你必須有這個功能。我唯一想到的就是某種丟失的手機定位應用程序。 – cost

+0

我真的不能。我已經爲這個項目簽署了NDA,但它是一個主要特點。如果我無法強制聲音忽略系統音量,我需要進行一些重大設計。 – romamnmlst

回答

13

我對鬧鐘應用程序有類似的需求。以下是有關量的評論的相關代碼。

當聲音配置文件設置爲靜音時,手動將鬧鐘流音量設置爲零並將鈴聲音量設置爲零時,這適用於我的HTC Rezound Android版本4.0.3。

Context context; 
    MediaPlayer mp; 
    AudioManager mAudioManager; 
    int userVolume; 


    public AlarmController(Context c) { // constructor for my alarm controller class 
     this.context = c; 
     mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 

     //remeber what the user's volume was set to before we change it. 
     userVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM); 

     mp = new MediaPlayer(); 
    } 
    public void playSound(String soundURI){ 

     Uri alarmSound = null; 
     Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); 


     try{ 
      alarmSound = Uri.parse(soundURI); 
     }catch(Exception e){ 
      alarmSound = ringtoneUri; 
     } 
     finally{ 
      if(alarmSound == null){ 
       alarmSound = ringtoneUri; 
      } 
     } 



     try { 

      if(!mp.isPlaying()){ 
      mp.setDataSource(context, alarmSound); 
      mp.setAudioStreamType(AudioManager.STREAM_ALARM); 
      mp.setLooping(true); 
      mp.prepare(); 
      mp.start(); 
      } 


     } catch (IOException e) { 
      Toast.makeText(context, "Your alarm sound was unavailable.", Toast.LENGTH_LONG).show(); 

     } 
     // set the volume to what we want it to be. In this case it's max volume for the alarm stream. 
     mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_PLAY_SOUND); 

    } 

    public void stopSound(){ 
// reset the volume to what it was before we changed it. 
     mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, userVolume, AudioManager.FLAG_PLAY_SOUND); 
     mp.stop(); 
     mp.reset(); 

    } 
    public void releasePlayer(){ 
     mp.release(); 
    } 
+0

非常感謝您對此完美! – romamnmlst

+0

thnx你爲我節省了很多時間! – mhdjazmati

0

播放從原文件夾中的音樂一個簡單而另類的方式;

try { 
     String uri = "android.resource://" + getPackageName() + "/" + R.raw.beep; 
     //Strign uri = "http://bla-bla-bla.com/bla-bla.wav" 
     Uri notification = Uri.parse(uri); 
     Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); 
     r.play(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }