我正试着播放一分钟的声音。我可以这样做,但我这样做的方式会生成声音缓冲区1然后播放它,这花费了太多时间,有一个很大的延迟。所以现在我正在尝试在播放时生成声音缓冲区。所以不会有任何延迟。它播放时间为4秒然后停止,但我不能再次点击我的按钮了。所以即使我听不到任何声音,我认为代码仍在运行。
这是我的代码:
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();
}
我尝试使用AudioTrackMode Stream 但是当程序到达Track.play时会抛出一个运行时错误: play()调用未初始化的AudioTrack。
所以我做错了什么?
答案 0 :(得分:0)
以下是基于android示例在c#中使用c#的简要版本:
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 ();
}
根据您的需要调整duration
和`freqOfTone`。