Adding a delay to android sound output - android

So I wrote this piece for an Android App. The idea is simple:
Detect whether sound is playing and if yes open the BluethoothSCO Channel so the audio gets played there.
I want to use it to "route" the navigation direction infos to my car speaker. It works nearly like expected.
There is a 'huge' delay of around 1 second between the audio recognition and the bluethoothsco connection being ready. This results in a loss of nearly half the navigation information.
My Idea was to add a delay or pause the playback for a second.
NOW: Sound is detected -> BluethootSCO opening (sound keeps playing here) -> sound over car speaker
IDEA: Sound is detected -> pause/delay for 1 sec ->BluethootSCO opening -> resume playback -> sound over car speaker
I thought about recording it and playing it afterwards but that would be to late for some informations like "turn left NOW".
A short delay would be ok, but I have no idea on to implement this :(
Since the app is only for myself using root would be ok.
Maybe there is an possibility direct at the AudioFlinger?
public void checkSound() {
AudioManager localAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
Visualizer localVisualizer = new Visualizer(0);
localVisualizer.setEnabled(true);
Visualizer.MeasurementPeakRms localPeak = new Visualizer.MeasurementPeakRms();
boolean wasPlayingBefore=false;
while (keeprunning) //Loop to detect changes on the Media Audio Stream
{
localVisualizer.getMeasurementPeakRms(localPeak);
if(localPeak.mPeak > -8500 && !wasPlayingBefore)
{
//There is some audio output
wasPlayingBefore=true;
localAudioManager.setBluetoothScoOn(true);
localAudioManager.startBluetoothSco();
localAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
android.os.SystemClock.sleep(5000); //Route to BT Headset will exist min. 5 seconds ...
}
if(localPeak.mPeak <= -8500 && wasPlayingBefore)
{
//output (temporary) gone
android.os.SystemClock.sleep(2000);//... plus this 2 seconds
//check again
localVisualizer.getMeasurementPeakRms(localPeak);
}
if(localPeak.mPeak <= -8500 && wasPlayingBefore)
{
//Audio didn't get back in last 2 seconds...
wasPlayingBefore=false;
localAudioManager.setBluetoothScoOn(false);
localAudioManager.stopBluetoothSco();
localAudioManager.setMode(AudioManager.MODE_NORMAL);
}
android.os.SystemClock.sleep(100); //Slow down the loop
Log.d("Peak", String.valueOf(localPeak.mPeak));//Debug info - Audio peak -9600 = Silent, 0 = MAX Output
}
localVisualizer.release();
}

Related

audio latency issues

In the application which I want to create, I face some technical obstacles. I have two music tracks in the application. For example, a user imports the music background as a first track. The second path is a voice recorded by the user to the rhythm of the first track played by the speaker device (or headphones). At this moment we face latency. After recording and playing back in the app, the user hears the loss of synchronisation between tracks, which occurs because of the microphone and speaker latencies.
Firstly, I try to detect the delay by filtering the input sound. I use android’s AudioRecord class, and the method read(). This method fills my short array with audio data.
I found that the initial values of this array are zeros so I decided to cut them out before I will start to write them into the output stream.
So I consider those zeros as a „warmup” latency of the microphone. Is this approach correct? This operation gives some results, but it doesn’t resolve the problem, and at this stage, I’m far away from that.
But the worse case is with the delay between starting the speakers and playing the music. This delay I cannot filter or detect. I tried to create some calibration feature which counts the delay. I play a „beep” sound through the speakers, and when I start to play it, I also begin to measure time. Then, I start recording and listen for this sound being detected by the microphone. When I recognise this sound in the app, I stop measuring time. I repeat this process several times, and the final value is the average from those results. That is how I try to measure the latency of the device. Now, when I have this value, I can simply shift the second track backwards to achieve synchronisation of both records (I will lose some initial milliseconds of the recording, but I skip this case, for now, there are some possibilities to fix it).
I thought that this approach would resolve the problem, but it turned out this is not as simple as I thought. I found two issues here:
1. Delay while playing two tracks simultaneously
2. Random in device audio latency.
The first: I play two tracks using AudioTrack class and I run method play() like this:
val firstTrack = //creating a track
val secondTrack = //creating a track
firstTrack.play()
secondTrack.play()
This code causes delays at the stage of playing tracks. Now, I don’t even have to think about latency while recording; I cannot play two tracks simultaneously without delays. I tested this with some external audio file (not recorded in my app) - I’m starting the same audio file using the code above, and I can see a delay. I also tried it with MediaPlayer class, and I have the same results. In this case, I even try to play tracks when callback OnPreparedListener invoke:
val firstTrack = //AudioPlayer
val secondTrack = //AudioPlayer
second.setOnPreparedListener {
first.start()
second.start()
}
And it doesn’t help.
I know that there is one more class provided by Android called SoundPool. According to the documentation, it can be better with playing tracks simultaneously, but I can’t use it because it supports only small audio files and that can't limit me.
How can I resolve this problem? How can I start playing two tracks precisely at the same time?
The second: Audio latency is not deterministic - sometimes it is smaller, and sometimes it’s huge, and it’s out of my hands. So measuring device latency can help but again - it cannot resolve the problem.
To sum up: is there any solution, which can give me exact latency per device (or app session?) or other triggers which detect actual delay, to provide the best synchronisation while playback two tracks at the same time?
Thank you in advance!
Synchronising audio for karaoke apps is tough. The main issue you seem to be facing is variable latency in the output stream.
This is almost certainly caused by "warm up" latency: the time it takes from hitting "play" on your backing track to the first frame of audio data being rendered by the audio device (e.g. headphones). This can have large variance and is difficult to measure.
The first (and easiest) thing to try is to use MODE_STREAM when constructing your AudioTrack and prime it with bufferSizeInBytes of data prior to calling play (more here). This should result in lower, more consistent "warm up" latency.
A better way is to use the Android NDK to have a continuously running audio stream which is just outputting silence until the moment you hit play, then start sending audio frames immediately. The only latency you have here is the continuous output latency.
If you decide to go down this route I recommend taking a look at the Oboe library (full disclosure: I am one of the authors).
To answer one of your specific questions...
Is there a way to calculate the latency of the audio output stream programatically?
Yes. The easiest way to explain this is with a code sample (this is C++ for the AAudio API but the principle is the same using Java AudioTrack):
// Get the index and time that a known audio frame was presented for playing
int64_t existingFrameIndex;
int64_t existingFramePresentationTime;
AAudioStream_getTimestamp(stream, CLOCK_MONOTONIC, &existingFrameIndex, &existingFramePresentationTime);
// Get the write index for the next audio frame
int64_t writeIndex = AAudioStream_getFramesWritten(stream);
// Calculate the number of frames between our known frame and the write index
int64_t frameIndexDelta = writeIndex - existingFrameIndex;
// Calculate the time which the next frame will be presented
int64_t frameTimeDelta = (frameIndexDelta * NANOS_PER_SECOND) / sampleRate_;
int64_t nextFramePresentationTime = existingFramePresentationTime + frameTimeDelta;
// Assume that the next frame will be written into the stream at the current time
int64_t nextFrameWriteTime = get_time_nanoseconds(CLOCK_MONOTONIC);
// Calculate the latency
*latencyMillis = (double) (nextFramePresentationTime - nextFrameWriteTime) / NANOS_PER_MILLISECOND;
A caveat: This method relies on accurate timestamps being reported by the audio hardware. I know this works on Google Pixel devices but have heard reports that it isn't so accurate on other devices so YMMV.
Following the answer of donturner, here's a Java version (that also uses other methods depending on the SDK version)
/** The audio latency has not been estimated yet */
private static long AUDIO_LATENCY_NOT_ESTIMATED = Long.MIN_VALUE+1;
/** The audio latency default value if we cannot estimate it */
private static long DEFAULT_AUDIO_LATENCY = 100L * 1000L * 1000L; // 100ms
/**
* Estimate the audio latency
*
* Not accurate at all, depends on SDK version, etc. But that's the best
* we can do.
*/
private static void estimateAudioLatency(AudioTrack track, long audioFramesWritten) {
long estimatedAudioLatency = AUDIO_LATENCY_NOT_ESTIMATED;
// First method. SDK >= 19.
if (Build.VERSION.SDK_INT >= 19 && track != null) {
AudioTimestamp audioTimestamp = new AudioTimestamp();
if (track.getTimestamp(audioTimestamp)) {
// Calculate the number of frames between our known frame and the write index
long frameIndexDelta = audioFramesWritten - audioTimestamp.framePosition;
// Calculate the time which the next frame will be presented
long frameTimeDelta = _framesToNanoSeconds(frameIndexDelta);
long nextFramePresentationTime = audioTimestamp.nanoTime + frameTimeDelta;
// Assume that the next frame will be written at the current time
long nextFrameWriteTime = System.nanoTime();
// Calculate the latency
estimatedAudioLatency = nextFramePresentationTime - nextFrameWriteTime;
}
}
// Second method. SDK >= 18.
if (estimatedAudioLatency == AUDIO_LATENCY_NOT_ESTIMATED && Build.VERSION.SDK_INT >= 18) {
Method getLatencyMethod;
try {
getLatencyMethod = AudioTrack.class.getMethod("getLatency", (Class<?>[]) null);
estimatedAudioLatency = (Integer) getLatencyMethod.invoke(track, (Object[]) null) * 1000000L;
} catch (Exception ignored) {}
}
// If no method has successfully gave us a value, let's try a third method
if (estimatedAudioLatency == AUDIO_LATENCY_NOT_ESTIMATED) {
AudioManager audioManager = (AudioManager) CRT.getInstance().getSystemService(Context.AUDIO_SERVICE);
try {
Method getOutputLatencyMethod = audioManager.getClass().getMethod("getOutputLatency", int.class);
estimatedAudioLatency = (Integer) getOutputLatencyMethod.invoke(audioManager, AudioManager.STREAM_MUSIC) * 1000000L;
} catch (Exception ignored) {}
}
// No method gave us a value. Let's use a default value. Better than nothing.
if (estimatedAudioLatency == AUDIO_LATENCY_NOT_ESTIMATED) {
estimatedAudioLatency = DEFAULT_AUDIO_LATENCY;
}
return estimatedAudioLatency
}
private static long _framesToNanoSeconds(long frames) {
return frames * 1000000000L / SAMPLE_RATE;
}
The android MediaPlayer class is notoriously slow to begin audio playback, I experienced an issue in an app I was creating where there was a greater than one second delay to begin playing an audio clip. I resolved it by switching to ExoPlayer which resulted in the playback starting within 100ms. I've also read that ffmpeg has even faster start audio startup time than ExoPlayer but I haven't used it so I can't make any promises.

Android - How to change sound output while playing sound?

I have an app that plays a list of soundtracks. It works great, however changing the sound output to internal speakers or vice versa, has no effect. It stops the current one, and then plays the next on the new mode.
I've read in android documentation of MediaPlayer that I can't change the sound output using setAudioStreamType() method. So this is the problem, but can't find a solution!
Here's the code for the toggle when the track is playing:
if (this.audioManager.isSpeakerphoneOn() || this.getCurrent() == 1) {
this.audioManager.setMode(AudioManager.MODE_IN_CALL);
this.audioManager.setSpeakerphoneOn(false);
this.mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
} else if (this.getCurrent() != 0) {
this.audioManager.setMode(AudioManager.MODE_NORMAL);
this.audioManager.setSpeakerphoneOn(true);
this.mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
Thanks in advance!

Play html5 audio sound when Phone screen is off

I am building a mobile optimized website and would like to play a sound after a counter is over. Usually, after 2 or more minutes.
The problem is that once the phone's screen is off, the phone disables my js, and prevents the audio from playing.
Potential Solution:
I read this
In the solution #3, u can loop 2 tracks sequentially, and the mobile phone will still play both even when screen is off.
So the trick I found is to use that loop, but have the first sound:
1. Be silence. Yes, complete 5min silence audio
2. have it loop as many times required before enough time has passed for second song to play.
So for instance, in here, silence audio will play twice before the other sound plays.
The trick is to control the max variable to achieved the desired output.
var count = 0;
var max = 2;
document.getElementById('silence_audio').addEventListener('ended', function () {
this.currentTime = 0;
this.pause();
if (count < max) {
document.getElementById('silence_audio').play();
count++;
} else {
document.getElementById('audio_4').play();
}
}, false);
document.getElementById('audio_4').addEventListener('ended', function () {
this.currentTime = 0;
this.pause();
document.getElementById('silence_audio').play();
}, false);
But my question is, are there any other better solutions?
Thank you!

Binding MediaPlayer to be played at a specific time

When using MediaPlayer, I noticed that whenever my phone stucks, the MediaPlayer glitches and then continues playing from the position in the audio it glitched.
This is bad for my implementation since I want the audio to be played at a specific time.
If I have a song of 1000 millisecond length, I want is the ability to set MediaPlayer to start playing at some specific time t, and then exactly stop at at time t+1000.
This means that I actually need two things:
1) Start MediaPlayer at a specific time with a very small delay.
2) Making MediaPlayer glitches ignore the audio they glitched on and continue playing in order to finish the song on time.
The delay of the functions is very important to me and I need the audio to be played exactly(~) at the time it was supposed to be played.
Thanks!
You will need to use possibly mp.getDuration(); and/or mp.getCurrentPosition(); although it's impossible to know exactly what you mean by "I need the audio to be played exactly(~) at the time it was supposed to be played."
Something like this should get you started:
int a = (mp.getCurrentPosition() + b);
Thanks for the answer Mike. but unfortunately this won't help me. Let's say that I asked MediaPlayer to start playing a song of length 3:45 at 00:00. At 01:00 I started using the phone's resources, due to the heavy usage my phone glitched making MediaPlayer pause for 2 seconds.
Time:
00:00-01:00 - I heard the audio at 00:00-01:00
01:00-01:02 - I heard silence because the phone glitched
01:02-03:47 - I heard the audio at 01:00-03:45 with 2 second time skew
Now from what I understood MediaPlayer is a bad choice of usage on this problem domain, since MediaPlayer provides a high level API.I am currently experimenting with the
AudioTrack class which should provide me with what I need:
//Creating a new audio track
AudioTrack audioTrack = new AudioTrack(...)
//Get start time
long start = System.currentTimeMillis();
// loop until finished
for (...) {
// Get time in song
long now = System.currentTimeMillis();
long nowInSong = now - start;
// get a buffer from the song at time nowInSong with a length of 1 second
byte[] b = getAudioBuffer(nowInSong);
// play 1 second of music
audioTrack.write(b, 0, b.length);
// remove any unplayed data
audioTrack.flush();
}
Now if I glitch I only glitch for 1 second and then I correct myself by playing the right audio at the right time!
NOTE
I haven't tested this code but it seems like the right way to do it. If it will actually work I will update this post again.
P.S. seeking in MediaPlayer is:
1. A heavy operation that will surely delay my music (every millisecond counts here)
2. Is not thread safe and cannot be used from multiple threads (seeks, starts etc...)

How to remove background Noise in Audio Track?

I am developing VOIP kind of application. Sending the voice is perfect but when i receive the same voice from the webserver, i am playing back that using AudioTrack API.
I am calling at.play() and at.write in a Thread so that i should get all the voice which is recorded and sent from the other device.
But, now the problem here i m facing is, if there is no voice than its still playing like some bullet sound, i mean there is a continuos background sound when i try to play .
I m using this following function in a Thread:
if (at != null) {
if (at.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
at.play();
} else {
if (playing == true) {
System.out.println("BEFORE WRITE");
at.write(playShortData, 0,
playShortData.length);
System.out.println("AFTER WRITE");
at.flush();
playing = false;
}
}
}
How can i remove the background noise if there no voice is send from other device.
I think its playing Junk value when none of them is speaking on other sides, its just sending junk values ..

Categories

Resources