一、使用
public class MainActivity extends AppCompatActivity {
private Hsvolume mHsVolume = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHsVolume = new Hsvolume(this);
mHsVolume.playMusic(R.raw.ceshi);
mHsVolume.setPlaySpeed(2.0F);
}
}
- 音频文件放置位置
二、Hsvolume 初始化音频类
public class Hsvolume {
private Context context;
private AudioManager mAudioManager;
private MediaPlayer mPlayer;
public Hsvolume(Context paramContext) {
this.context = paramContext;
this.mAudioManager = ((AudioManager) paramContext.getSystemService(Context.AUDIO_SERVICE));
}
public void playMusic(int paramInt) {
stopMusic();
this.mPlayer = MediaPlayer.create(this.context, paramInt);
if (this.mPlayer != null) {
this.mPlayer.setLooping(false);
this.mPlayer.start();
}
}
public boolean setPlaySpeed(float speed) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
PlaybackParams params = mPlayer.getPlaybackParams();
params.setSpeed(speed);
mPlayer.setPlaybackParams(params);
return true;
} catch (Exception e) {
return false;
}
}
return false;
}
public void setSystemvolume(float b) {
if (this.mAudioManager != null) {
int max=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
this.mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (b*max), 0);
saveVolume((int) (b*max));
}
}
public void saveVolume(int paramInt) {
Uri localUri = Settings.System.getUriFor(Settings.System.AUTO_TIME);
Settings.System.putInt(this.context.getContentResolver(), Settings.System.AUTO_TIME, paramInt);
this.context.getContentResolver().notifyChange(localUri, null);
}
public void setTouchvolume(boolean isChecked) {
ContentResolver contentResolver;
if (this.mAudioManager != null) {
this.mAudioManager.loadSoundEffects();
contentResolver = this.context.getContentResolver();
if (!(isChecked))
Settings.System.putInt(contentResolver, Settings.System.SOUND_EFFECTS_ENABLED, 0);
else{
Settings.System.putInt(contentResolver, Settings.System.SOUND_EFFECTS_ENABLED, 1);
}
if (!isChecked) {
this.mAudioManager.unloadSoundEffects();
return;
}
}
}
public void stopMusic() {
if (this.mPlayer != null) {
this.mPlayer.stop();
this.mPlayer.release();
this.mPlayer = null;
}
}
}