下面列出了android.media.AudioManager#STREAM_MUSIC 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void buildRenderers(DemoPlayer player) {
Allocator allocator = new DefaultAllocator(BUFFER_SEGMENT_SIZE);
Handler mainHandler = player.getMainHandler();
// Build the video and audio renderers.
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(mainHandler, null);
DataSource dataSource = new DefaultUriDataSource(context, bandwidthMeter, userAgent);
ExtractorSampleSource sampleSource = new ExtractorSampleSource(uri, dataSource, allocator,
BUFFER_SEGMENT_COUNT * BUFFER_SEGMENT_SIZE, mainHandler, player, 0);
MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(context,
sampleSource, MediaCodecSelector.DEFAULT, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT, 5000,
mainHandler, player, 50);
MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource,
MediaCodecSelector.DEFAULT, null, true, mainHandler, player,
AudioCapabilities.getCapabilities(context), AudioManager.STREAM_MUSIC);
TrackRenderer textRenderer = new TextTrackRenderer(sampleSource, player,
mainHandler.getLooper());
// Invoke the callback.
TrackRenderer[] renderers = new TrackRenderer[DemoPlayer.RENDERER_COUNT];
renderers[DemoPlayer.TYPE_VIDEO] = videoRenderer;
renderers[DemoPlayer.TYPE_AUDIO] = audioRenderer;
renderers[DemoPlayer.TYPE_TEXT] = textRenderer;
player.onRenderers(renderers, bandwidthMeter);
}
@Override
public void onFinish() {
if (vibrateEnabled)
vibrator.vibrate(vibrateDuration);
if (toneEnabled) {
try {
this.toneGenerator = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
toneGenerator.startTone(toneCode, toneDuration);
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (toneGenerator != null) {
Log.d("Countdown", "toneGenerator released");
toneGenerator.release();
toneGenerator = null;
}
}
}, toneDuration);
} catch (Exception e) {
Log.d("Countdown", "Exception while playing sound:" + e);
}
}
}
public AudioThread(int sampleRateInHz, int channel, long streamId, long decoderId, Media media)
{
if (channel == 1)
{
channel_configuration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
} else
{
channel_configuration = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
}
this.mediaStreamId = streamId;
this.decoderId = decoderId;
this.media = media;
int minBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channel_configuration, AudioFormat.ENCODING_PCM_16BIT);
if (minBufferSize > audioLength)
{
audioLength = minBufferSize;
}
mAudioBuffer = new byte[audioLength];
mAudio = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channel_configuration, AudioFormat.ENCODING_PCM_16BIT, audioLength, AudioTrack.MODE_STREAM);
}
@CalledByNative
private boolean configureAudio(MediaFormat format, MediaCrypto crypto, int flags,
boolean playAudio) {
try {
mMediaCodec.configure(format, null, crypto, flags);
if (playAudio) {
int sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
int channelCount = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
int channelConfig = (channelCount == 1) ? AudioFormat.CHANNEL_OUT_MONO :
AudioFormat.CHANNEL_OUT_STEREO;
// Using 16bit PCM for output. Keep this value in sync with
// kBytesPerAudioOutputSample in media_codec_bridge.cc.
int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig,
AudioFormat.ENCODING_PCM_16BIT);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channelConfig,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
}
return true;
} catch (IllegalStateException e) {
Log.e(TAG, "Cannot configure the audio codec " + e.toString());
}
return false;
}
public TimerView(Context context, AttributeSet attrs, int style) {
super(context, attrs, style);
mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
mTimerFinishedSoundId = mSoundPool.load(context, R.raw.timer_finished, SOUND_PRIORITY);
LayoutInflater.from(context).inflate(R.layout.card_timer, this);
mHoursView = (TextView) findViewById(R.id.hours);
mMinutesView = (TextView) findViewById(R.id.minutes);
mSecondsView = (TextView) findViewById(R.id.seconds);
mTipView = (TextView) findViewById(R.id.tip);
mTipView.setText(context.getResources().getString(R.string.timer_finished));
mTipView.setVisibility(View.INVISIBLE);
mWhiteColor = context.getResources().getColor(R.color.white);
mRedColor = context.getResources().getColor(R.color.red);
}
public boolean setPlayer(int rate)
{
int bufferSizePlayer = AudioTrack.getMinBufferSize(rate, AudioFormat.CHANNEL_OUT_MONO, audioFormat);
Log.d("====buffer Size player ", String.valueOf(bufferSizePlayer));
player= new AudioTrack(AudioManager.STREAM_MUSIC, rate, AudioFormat.CHANNEL_OUT_MONO, audioFormat, bufferSizePlayer, AudioTrack.MODE_STREAM);
if (player.getState() == AudioTrack.STATE_INITIALIZED)
{
return true;
}
else
{
return false;
}
}
@SuppressLint("NewApi")
private int audioTrackInit(int sampleRateInHz, int channels) {
// this.sampleRateInHz=sampleRateInHz;
// this.channels=channels;
// return 0;
audioTrackRelease();
int channelConfig = channels >= 2 ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO;
try {
mAudioTrackBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, AudioFormat.ENCODING_PCM_16BIT);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfig, AudioFormat.ENCODING_PCM_16BIT, mAudioTrackBufferSize, AudioTrack.MODE_STREAM);
} catch (Exception e) {
mAudioTrackBufferSize = 0;
Log.e("audioTrackInit", e);
}
return mAudioTrackBufferSize;
}
@Override
public void onReceive(Context context, Intent intent) {
if (VOLUME_CHANGED_ACTION.equals(intent.getAction()) && (intent.getIntExtra(EXTRA_VOLUME_STREAM_TYPE, -1) == AudioManager.STREAM_MUSIC)) {
VolumeChangerObserver observer = mObserverWeakReference.get();
if (observer == null) {
return;
}
VolumeChangeListener listener = observer.getVolumeChangeListener();
if (listener == null) {
return;
}
int volume = observer.getCurrentMusicVolume();
if (volume >= 0) {
listener.onVolumeChanged(getMaxMusicVolume(), volume);
}
}
}
private void init() {
finder = ResoureFinder.getInstance(getContext());
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
soundId = soundPool.load(getContext(), finder.getRawId("collision"), 1);
touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
DisplayMetrics dm = getResources().getDisplayMetrics();
bitmapBall = BitmapFactory.decodeResource(getResources(), finder.getDrawableId("platform_myspace_ball"));
bitmapHole = BitmapFactory.decodeResource(getResources(), finder.getDrawableId("platform_myspace_hole"));
bitmapW = bitmapBall.getWidth();
bitmapH = bitmapBall.getHeight();
radius = bitmapW / 2;
dissAreaLeft = 200 * dm.density;
dissAreaTop = 50 * dm.density;
dissAreaRight = dissAreaLeft + bitmapHole.getWidth();
dissAreaBottom = dissAreaTop + bitmapHole.getHeight();
activity = (Activity) getContext();
Rect rectgle = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
windowWidth = rectgle.width();
windowHeight = rectgle.height();
mVibrator = (Vibrator) activity.getApplication().getSystemService(Service.VIBRATOR_SERVICE);
sm = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
setBackgroundDrawable(finder.getDrawable("platform_myspace_gsense_bg_shape"));
params = new WindowManager.LayoutParams();
params.height = windowHeight;
params.width = windowWidth;
params.type = WindowManager.LayoutParams.TYPE_APPLICATION | WindowManager.LayoutParams.FIRST_SUB_WINDOW;
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_BLUR_BEHIND;// 模态,不能获得焦点,背景失焦
params.alpha = 1.0f;
params.format = PixelFormat.TRANSPARENT;
params.gravity = Gravity.LEFT | Gravity.TOP;
params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
params.x = dm.widthPixels - windowWidth;
params.y = dm.heightPixels - windowHeight;
params.windowAnimations = finder.getStyleId("Anim_platform_myspace_fade");
}
/** @return True if safe volume won't have an effect on this volume change event. */
public boolean checkSafeMediaVolume(int streamType, int index, int device) {
if ((streamType == AudioManager.STREAM_MUSIC) &&
((device & mSafeMediaVolumeDevices) != 0) &&
((index - mSafeMediaVolumeIndex) == 1)) {
return false;
}
return true;
}
private void muteVolume() {
int[] volumes = new int[]{AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM, AudioManager.STREAM_RING, AudioManager.STREAM_MUSIC, AudioManager.STREAM_NOTIFICATION};
for (int volumeType : volumes) {
audio.setStreamMute(volumeType, true);
}
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
}
private void initializeSounds() {
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load sounds
mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mLoaded = true;
}
});
mSoundConnect = mSoundPool.load(this, R.raw.proxima, 1);
mSoundDisconnect = mSoundPool.load(this, R.raw.tejat, 1);
}
/**
* Initializes the audio track for writing new buffers using {@link #handleBuffer}.
*
* @param sessionId Audio track session identifier to re-use, or {@link #SESSION_ID_NOT_SET} to
* create a new one.
* @return The new (or re-used) session identifier.
*/
public int initialize(int sessionId) throws InitializationException {
// If we're asynchronously releasing a previous audio track then we block until it has been
// released. This guarantees that we cannot end up in a state where we have multiple audio
// track instances. Without this guarantee it would be possible, in extreme cases, to exhaust
// the shared memory that's available for audio track buffers. This would in turn cause the
// initialization of the audio track to fail.
releasingConditionVariable.block();
if (sessionId == SESSION_ID_NOT_SET) {
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM);
} else {
// Re-attach to the same audio session.
audioTrack = new android.media.AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, encoding, bufferSize, android.media.AudioTrack.MODE_STREAM, sessionId);
}
checkAudioTrackInitialized();
if (Util.SDK_INT >= 19) {
audioTrackUtil = new AudioTrackUtilV19(audioTrack);
} else {
audioTrackUtil = new AudioTrackUtil(audioTrack);
}
setVolume(volume);
return audioTrack.getAudioSessionId();
}
boolean updateRingerModeAffectedStreams(Context context) {
int ringerModeAffectedStreams;
// make sure settings for ringer mode are consistent with device type: non voice capable
// devices (tablets) include media stream in silent mode whereas phones don't.
ringerModeAffectedStreams = Settings.System.getInt(context.getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED,
((1 << AudioManager.STREAM_RING)|(1 << AudioManager.STREAM_NOTIFICATION)|
(1 << AudioManager.STREAM_SYSTEM)));
// ringtone, notification and system streams are always affected by ringer mode
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_RING)|
(1 << AudioManager.STREAM_NOTIFICATION)|
(1 << AudioManager.STREAM_SYSTEM);
if (mVoiceCapable) {
ringerModeAffectedStreams &= ~(1 << AudioManager.STREAM_MUSIC);
} else {
ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
}
if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
mRingerModeAffectedStreams = ringerModeAffectedStreams;
return true;
}
return false;
}
private void reInitAudioTrack() {
try {
mMusicAudioTrack =
new AudioTrack(AudioManager.STREAM_MUSIC, mPreMediaSampleRate, mPreMediaChannelConfig,
mPreMediaFormate, mPreMinBuffSize, AudioTrack.MODE_STREAM);
} catch (IllegalArgumentException e) {
informMusicPause();
mMusicAudioTrack = null;
e.printStackTrace();
}
}
public SoundFactory(Context context, SoundManager soundManager) {
mContext = context;
mSoundManager = soundManager;
mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
mSoundMap = new HashMap<>();
// FIXME: This is a workaround because the first explosion effect has no sound otherwise
createSound(R.raw.explosive3_bghgh);
}
protected void createSoundPool() {
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
mBeepId = mSoundPool.load(this, R.raw.beep, 1);
}
private void streamAudio(final Socket socket) throws IllegalArgumentException, IllegalStateException, IOException
{
Log.i(TAG, "Setting up stream");
final int frequency = 11025;
final int channelConfiguration = AudioFormat.CHANNEL_OUT_MONO;
final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
final int bufferSize = AudioTrack.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
final int byteBufferSize = bufferSize*2;
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
frequency,
channelConfiguration,
audioEncoding,
bufferSize,
AudioTrack.MODE_STREAM);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
final InputStream is = socket.getInputStream();
int read = 0;
audioTrack.play();
try
{
final byte [] buffer = new byte[byteBufferSize];
while(socket.isConnected() && read != -1 && Thread.currentThread().isInterrupted() == false)
{
read = is.read(buffer);
if(read > 0)
{
audioTrack.write(buffer, 0, read);
}
}
}
finally
{
audioTrack.stop();
socket.close();
}
}
public MyPlayer play() {
if (sound.size() == 0) return this;
mediaPlayers = new MediaPlayer[sound.size()];
for (int i = 0; i < sound.size(); i++) {
Sound s = sound.get(i);
mediaPlayers[i] = s.createMediaPlayer(alarm);
mediaPlayers[i].setAudioStreamType(getStreamType());
try {
mediaPlayers[i].prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
for (int i = sound.size() - 2; i >= 0; i--) {
mediaPlayers[i].setNextMediaPlayer(mediaPlayers[i + 1]);
}
final AudioManager am = (AudioManager) App.get().getSystemService(Context.AUDIO_SERVICE);
final int streamType;
final int oldvol = am.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume < 0) {
streamType = getStreamType();
} else {
streamType = AudioManager.STREAM_MUSIC;
am.setStreamVolume(streamType, volume, 0);
}
mediaPlayers[0].start();
setupSeekbar();
mediaPlayers[mediaPlayers.length - 1].setOnCompletionListener(mp -> {
if (volume > 0) {
am.setStreamVolume(streamType, oldvol, 0);
}
if (onComplete != null) {
onComplete.onComplete();
}
});
return this;
}
@SuppressWarnings("deprecation")
private void createSoundPoolOld(){
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
}