Reputation: 37
I am trying to play one minute of sound. I can do that, but the way I was doing it would generate the sound buffer 1st then play it and that was taking too much time, there was a big delay. so now I am trying to generate the sound buffer while playing it.so there would be no delay. It plays for like 4 secs and then stops, but I can't click my button again for like a min. so I think the code is still running even though I can't hear anything.
here is my code:
public void play()
{
short[] buffer = new short[44100];
track = new AudioTrack (Stream.Music, 44100, ChannelOut.Mono, Encoding.Pcm16bit, 5292000, AudioTrackMode.Static);
track.SetPlaybackRate (44100);
while (n2 < 5292000) {
for (int n = 0; n < 44100; n++) {
float temp1 = (float)( Amplitude * Math.Sin ((2 * Math.PI * Frequency * n2) / 44100D));
byte[] bytes = BitConverter.GetBytes (temp1);
buffer [n] = (short)(temp1 * short.MaxValue);
n2++;
}
int buffer_number = track.Write (buffer, 0, buffer.Length);
track.Play();
}
track.Release();
}
I tried to use AudioTrackMode Stream but when the program get to Track.play is throw a runtime error: play() called on uninitialized AudioTrack.
so what am I doing wrong?
Upvotes: 0
Views: 1874
Reputation: 1040
Here is a condensed version of how I got it to work in c# based on the android sample at:
http://marblemice.blogspot.fr/2010/04/generate-and-play-tone-in-android.html
public void playSound()
{
var duration = 1;
var sampleRate = 8000;
var numSamples = duration * sampleRate;
var sample = new double[numSamples];
var freqOfTone = 1900;
byte[] generatedSnd = new byte[2 * numSamples];
for (int i = 0; i < numSamples; ++i) {
sample[i] = Math.Sin(2 * Math.PI * i / (sampleRate/freqOfTone));
}
int idx = 0;
foreach (double dVal in sample) {
short val = (short) (dVal * 32767);
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >> 8);
}
var track = new AudioTrack (global::Android.Media.Stream.Music, sampleRate, ChannelOut.Mono, Encoding.Pcm16bit, numSamples, AudioTrackMode.Static);
track.Write(generatedSnd, 0, numSamples);
track.Play ();
}
Adjust duration
and `freqOfTone``acording to your needs.
Upvotes: 1