I want to stream an audio file from my android device to another via the MediaRouter Class. As far as I understood I need the
mediarouter.addCallback(MediaRouter.ROUTE_TYPE_LIVE_AUDIO, mCallback);
function to listen if a connected Device is playing audio. However I'm not sure about that.
My Question is how do I get the audio stream ?
If you play your audio using AudioTrack you need to make sure that the streamType matches the route's streamType. To get the route's streamType, simply do:
private final MediaRouter.Callback mMediaRouterCallback =
new MediaRouter.Callback() {
#Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo route) {
Log.i(TAG, "streamType = " + route.getPlaybackStream());
}
};
Usually it will be AudioManager.STREAM_MUSIC. So when you initialize your AudioTrack make sure to:
_audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRate,
channelConfig,
audioFormat,
bufferSize,
mode);
Related
I have an Android app where there is some raw audio bytes stored in a variable.
If I use an AudioTrack to play this audio data, it only works if I use AudioTrack.MODE_STREAM:
byte[] recordedAudioAsBytes;
public void playButtonPressed(View v) {
// this verifies that audio data exists as expected
for (int i=0; i<recordedAudioAsBytes.length; i++) {
Log.i("ABC", "byte[" + i + "] = " + recordedAudioAsBytes[i]);
}
// STREAM MODE ACTUALLY WORKS!!
/*
AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLERATE, CHANNELS,
ENCODING, MY_CHOSEN_BUFFER_SIZE, AudioTrack.MODE_STREAM);
player.play();
player.write(recordedAudioAsBytes, 0, recordedAudioAsBytes.length);
*/
// STATIC MODE DOES NOT WORK
AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLERATE, PLAYBACK_CHANNELS,
ENCODING, MY_CHOSEN_BUFFER_SIZE, AudioTrack.MODE_STATIC);
player.write(recordedAudioAsBytes, 0, recordedAudioAsBytes.length);
player.play();
}
If I use AudioTrack.MODE_STATIC, the output is glitchy -- it just makes a nasty pop and sounds very short with hardly anything audible.
So why is that? Does STATIC_MODE require that the audio data have a header?
That's all I can think of.
If you'd like to see all the code, check this question.
It seems to me that you are using the same MY_CHOSEN_BUFFER_SIZE for 'streaming' and 'static' mode!? This might explain why it sounds short...
In order to use Audiotracks 'static-mode' you have to use the size of your Byte-Array (bigger will also work) as buffersize. The Audio will be treated as one big chunk of data.
See: AudioTrack.Builder
setBufferSizeInBytes()... "If using the AudioTrack in static mode (see AudioTrack#MODE_STATIC), this is the maximum size of the sound that will be played by this instance."
In my application audio recorded in a Foreground service. I start recording after Bluetooth SCO is connected. Its working fine form Android KitKat to Nougat. But when I tried with Huawei Honor 8 (Android Oreo), audio is recording from phone microphone instead of Bluetooth headset microphone. When I tried on Google pixel 2, the recording not works at all.
Start Bluetooth SCO
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
Log.d(TAG, "Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
am.setBluetoothScoOn(true);
unregisterReceiver(this);
startRecord();
}
}
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
am.startBluetoothSco();
AudioRecord config
final int RECORDER_SAMPLERATE = 8000;
final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
Android has changed the length of data for communication via bluetooth. Check out https://developer.android.com/about/versions/oreo/android-8.0-changes
To resolve this many OEMs are suggesting that you might need to wipe the device cache.
https://forums.oneplus.com/threads/bluetooth-audio-is-ruined-after-oreo-update.699589/
Check this quick fix guide https://www.theandroidsoul.com/fix-android-oreo-bluetooth-issues/
10 common fixes for android oreo issues. https://www.gottabemobile.com/android-oreo-problems-fixes/
Rebooting in safe mode. https://support.google.com/android/answer/7665064?hl=en&ref_topic=6023296&visit_id=1-636636939996434821-3584672143&rd=1
Let me know if this helps.
I has this problem in Huawei Honor 9i too.
I found recording from phone microphone instead of Bluetooth device microphone too, but when I opened a music application played music in background, the Bluetooth microphone works.
So I try to play a blank background music when I starting the recorder, it works well.
I use AudioRecord to record music but when I record it uses the phone mic.
how can I force him to use the channel of the Headphone?
I use this code:
int minSize = AudioRecord.getMinBufferSize(8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord ar = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, minSize);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
recorder[0] = false;
}
}, timeInSecondsToRecord * 1000);
short[] buffer = new short[minSize];
ar.startRecording();
Log.d("Started","Reording");
while (recorder[0]) {
ar.read(buffer, 0, minSize);
for (short s : buffer) {
if (s>1000)
System.out.println("signalVal=" + s);
}
}
Log.d("Finished","Reording");
ar.stop();
Thank you
You can use AudioManager.isWiredHeadsetOn() for checking if the headset are plugged in or not. If the above value is false dont perform any action or whatever you want to do. And also you need permission first: MODIFY_AUDIO_SETTINGS
Hope this helps. :)
I had this problem in reverse (trying to force use of the phone's mic instead of the headphone mic). You can choose a mic by scanning the AudioDeviceInfo array in AudioManager. Here's what I think it would look like for you (if TYPE_LINE_ANALOG doesn't work, check out the AudioDeviceInfo page for more possibilities or debug what devices come up):
AudioRecord audioRecord =
new AudioRecord(...);
// Force use of the line in mic
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
for ( AudioDeviceInfo device : audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)) {
if ( device.getType() == AudioDeviceInfo.TYPE_LINE_ANALOG) {
audioRecord.setPreferredDevice(device);
break;
}
}
Basically, my program records user input via the microphone and store it as a .pcm file in the sdcard/ directory. It'll be overwritten should there be an existing one. The file is then later sent for playback and analysis (mainly FFT, RMS computation).
I have added another function which allows the program to record system audio, so it allows user's mp3 files to be analyzed as well. It streams the system audio and store it as a .pcm file for later playback and analysis.
It's all functioning well. However, there's a slight issue, when the program streams audio, it captures input from the mic and there'll be noises in the playback. I do not want this as it'll affect the analysis reading. I googled for a solution and found that I can actually mute the mic. So now, I want to mute the mic when the mp3 file is being streamed.
The code I have found is,
AudioManager.setMicrophoneMute(true);
I tried to implement it but it just crashes my application. I tried to find for solutions these few days but I cannot seem to get any.
Here is my code snippet for the part where I want to stream system audio and muting the microphone before it starts streaming.
//create a new AudioRecord object to record the audio data of an mp3 file
int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
audioRecord = new AudioRecord(AudioManager.STREAM_MUSIC,
frequency, channelConfiguration,
audioEncoding, bufferSize);
//a short array to store raw pcm data
short[] buffer = new short[bufferSize];
Log.i("decoder", "The audio record created fine ready to record");
try {
audioManager.setMicrophoneMute(true);
} catch (Exception e) {
e.printStackTrace();
}
audioRecord.startRecording();
isDecoding = true;
When the setMicrophoneMute(true) line is surrounded with try-catch, the program would only crash when I want to send the recording for play back. Errors are as follow:
"AudioFlinger could not create track, status: -12"
"Error initializing AudioTrack"
"[android.media.AudioTrack] Error code -20 when initializing AudioTrack."
When it is not surrounded with try-catch, the program would just crash the moment I click on the start streaming button.
"Decoding failed" < this is an error log from catching a throwable.
How can I mute the microphone input while streaming the system audio? Let me know if I can provide you with more codes. Thank you!
**EDIT
I have implemented my mutemicrophone successfully, it even returns me a true for isMicrophoneMute(), however, it's not muted as it still records from the microphone; it's a false true.
Based on the suggested answer, I have already created a class for audio focus as below:
private final Context c;
private final AudioManager.OnAudioFocusChangeListener changeListener =
new AudioManager.OnAudioFocusChangeListener()
{
public void onAudioFocusChange(int focusChange)
{
//nothing to do
}
};
AudioFocus(Context context)
{
c = context;
}
public void grabFocus()
{
final AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
final int result = am.requestAudioFocus(changeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
Log.d("audiofocus","Grab audio focus: " + result);
}
public void releaseFocus()
{
final AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
final int result = am.abandonAudioFocus(changeListener);
Log.d("audiofocus","Abandon audio focus: " + result);
}
I then call the method from my Decoder class to request for audio focus:
int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
audioFocus.grabFocus();
audioRecord = new AudioRecord(AudioManager.STREAM_MUSIC,
frequency, channelConfiguration,
audioEncoding, bufferSize);
//a short array to store raw pcm data
short[] buffer = new short[bufferSize];
Log.i("decoder", "The audio record created fine ready to record");
audioRecord.startRecording();
isDecoding = true;
Log.i("decoder", "Start recording fine");
And then release the focus when stop decoding is pressed:
//stops recording
public void stopDecoding(){
isDecoding = false;
Log.i("decoder", "Out of recording");
audioRecord.stop();
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
mp.stop();
mp.release();
audioFocus.releaseFocus();
}
However, this makes my application crash. Where did I went wrong?
The following snippet requests permanent audio focus on the music audio stream. You should request the audio focus immediately before you begin playback, such as when the user presses play. I think this would be the way to go rather than muting the input microphone. Check out the developer audio focus docs for more information
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
...
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
// Start playback.
}
I currently have code that reads a recording in from the devices mic using the AudioRecord class and then playing it back out using the AudioTrack class.
My problem is that when I play it out it plays via the speaker phone.
I want it to play out via the ear piece on the device.
Here is my code:
public class LoopProg extends Activity {
boolean isRecording; //currently not used
AudioManager am;
int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setMicrophoneMute(true);
while(count <= 1000000){
Record record = new Record();
record.run();
count ++;
Log.d("COUNT", "Count is : " + count);
}
}
public class Record extends Thread{
static final int bufferSize = 200000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
public void run() {
isRecording = true;
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize);
AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM);
am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC);
int ok = am.getRouting(AudioManager.ROUTE_EARPIECE);
Log.d("ROUTING", "getRouting = " + ok);
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
//am.setSpeakerphoneOn(true);
Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
am.setSpeakerphoneOn(false);
Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn());
atrack.setPlaybackRate(11025);
byte[] buffer = new byte[buffersize];
arec.startRecording();
atrack.play();
while(isRecording) {
arec.read(buffer, 0, buffersize);
atrack.write(buffer, 0, buffer.length);
}
arec.stop();
atrack.stop();
isRecording = false;
}
}
}
As you can see if the code I have tried using the AudioManager class and its methods including the deprecated setRouting method and nothing works, the setSpeakerphoneOn method seems to have no effect at all, neither does the routing method.
Has anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone?
Just got it to work on 2.2. I still needed the In_Call setup which I don't really like but I'll deal with it for now. I was able to ditch the call routing stuff which is deprecated now. I found you definitely need the Modify_Audio_Settings permission, no error without it but it the setSpeakerPhone method just does nothing. Here is the mock up of the code I used.
private AudioManager m_amAudioManager;
m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
m_amAudioManager.setMode(AudioManager.MODE_IN_CALL);
m_amAudioManager.setSpeakerphoneOn(false);
Please use this code, works well:
//PLAY ON EARPIECE
mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(false);
//PLAY ON SPEAKER
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
There was some related discussion in this recent question:
Android - can I mute currently playing audio applications?
Based on the AudioManager source code, it seems that you must be in "call mode" before the setSpeakerphoneOn method has any effect.
However, I recently saw an application that could seamlessly switch between earpiece and speakerphone while still showing the current stream as the "media" stream, so I would be interested in any further answers.
Misleaded by some answers here for quite a lot of time. I'm using Android 2.2. "audioManager.setSpeakerphoneOn(false);" is working.
audioManager.setSpeakerphoneOn(false);
...
mediaPlayer.setDataSource(..);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mediaPlayer.prepare();
public MediaPlayer m_mpSpeakerPlayer;
private AudioManager m_amAudioManager;
m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// 從Receiver Earpiece發音
m_amAudioManager.setSpeakerphoneOn(false);
m_amAudioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
Log.i(TAG, String.valueOf(m_amAudioManager.getRouting(AudioManager.ROUTE_EARPIECE)));
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
// 把聲音設定成從Earpiece出來
// 重點在這行,要把它設定為正在通話中
m_amAudioManager.setMode(AudioManager.MODE_IN_CALL);
// 開始放音樂
m_mpSpeakerPlayer.reset();
m_mpSpeakerPlayer.setDataSource("sdcard/receiver.mp3");
m_mpSpeakerPlayer.prepare();
m_mpSpeakerPlayer.start();
//最後再把它設定從Speaker放音,達成!
m_amAudioManager.setMode(AudioManager.MODE_NORMAL);
I appear to have got it working on 1.6.
So I said I'd post here how I done it.
To get it working in 1.6 I:
Used the AudioManager class to set setSpeakerphoneOn(false), I then used the Voice_Call_Stream and add volume control to the Voice_Call_Stream.
The setSpeakerphoneOn(false) method is used in onCreate() of the activity and this appears to route to the headset, I then used a button and used the setSpeakerphoneOn(true) method and the audio gets routed to the speaker.
The method only appears to work when it is used in onCreate() for me and I haven't tested it extensively but for the moment it allows me to switch between headset and speaker on a 1.6 device
now in 2022 in Android S (12, API31) setSpeakerphoneOn(false) isn't working reliablie, it is in fact deprecated! instead we can use new API and setCommunicationDevice(AudioDeviceInfo) method. (works with AudioManager.STREAM_VOICE_CALL)
some sample
Boolean result = null;
ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}
AudioDeviceInfo currentDevice = audioManager.getCommunicationDevice();
if (currentDevice!=null) {
for (Integer targetType : targetTypes) {
if (targetType == currentDevice.getType()) {
Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType ALREADY SET UP!!");
result = true;
break;
}
}
}
if (result == null) {
List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
outer:
for (Integer targetType : targetTypes) {
for (AudioDeviceInfo device : devices) {
if (device.getType() == targetType) {
result = audioManager.setCommunicationDevice(device);
Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
if (result) break outer;
}
}
}
}
if (result == null) {
Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
}
else if (!result) {
Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType FAILED TO SET!!");
}
If the ear piece is connected to the phone with bluetooth (which I assume it is), have you tried calling AudioManager.setBluetoothScoOn(true)?
I've been through the Android reference and this is the only thing I could find that you didn't mention trying.