问题
I am new to Android Auto and still trying to figure it out. I have successfully played music from my own programmed app but the music is coming out from my smartphone speakers instead of car speakers. Other (sample) apps do it the right way.
Which part of of the Media System is responsible to handle this behaviour? Android documentation says the sound is sent to the car speakers.
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
this.mPlayingQueue.add(item);
session.setActive(true);
session.setQueue(mPlayingQueue);
session.setQueueTitle("My Queue");
session.setPlaybackState(buildState(PlaybackState.ACTION_PLAY));
session.setMetadata(createRammsteinMetaData());
this.mediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.rammstein_sonne);
this.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (tryToGetAudioFocus()) {
this.mediaPlayer.start();
Log.d("AUDIOTAG", "Playing");
} else {
Log.d("AUDIOTAG", "Playing not possible, no focus");
}
}
private boolean tryToGetAudioFocus() {
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
Thanks in advance. Orrimp
回答1:
There seems to be a pretty big bug there! Local music from resources does not play properly using MediaPlayer.create(...);
Thx Reaz Murshed I just tried to use the STREAM_MUSIC as a real stream with Internet Music and it works. Translate to use setDataSource with Resource URI! Use the following snippet:
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
/* Set session stuff like queue, metadata and so on*/
Uri myUri = resourceToUri(getBaseContext(), R.raw.rammstein_sonne);
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getBaseContext(), myUri);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (tryToGetAudioFocus()) {
mediaPlayer.start();
Log.d("AUDIOTAG", "Playing");
} else {
Log.d("AUDIOTAG", "Playing not possible, no focus");
}
}
});
} catch (IOException e) {
e.printStackTrace();
Log.d("AUTO", "EERORROR");
}
}
public Uri resourceToUri(Context context, int resID) {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.getResources().getResourcePackageName(resID) + '/' +
context.getResources().getResourceTypeName(resID) + '/' +
context.getResources().getResourceEntryName(resID));
}
来源:https://stackoverflow.com/questions/34808725/sound-plays-from-smarthpone-speakers-instead-android-auto-speakers