C# Android和RecordAudio:如何将文件写入和其他任务结合起来
我开发了一个Xamarin.Android应用程序,我需要在.wav中录制一个音频文件,同时显示相关的频谱图 我能够分别执行两项任务,但不能将它们组合在一起 我使用C# Android和RecordAudio:如何将文件写入和其他任务结合起来,c#,arrays,xamarin.android,streamwriter,audiorecord,C#,Arrays,Xamarin.android,Streamwriter,Audiorecord,我开发了一个Xamarin.Android应用程序,我需要在.wav中录制一个音频文件,同时显示相关的频谱图 我能够分别执行两项任务,但不能将它们组合在一起 我使用录音通过麦克风录制声音: public async Task StartRecording() { audioRecord = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, bufferSi
录音
通过麦克风录制声音:
public async Task StartRecording()
{
audioRecord = new AudioRecord(AudioSource.Mic, 44100, ChannelIn.Mono, Android.Media.Encoding.Pcm16bit, bufferSize);
if (audioRecord.State == State.Initialized)
audioRecord.StartRecording();
isRecording = true;
recordingThread = new System.Threading.Thread(new ThreadStart(
WriteAudioDataToFile
));
recordingThread.Start();
}
文件写入在WriteAudioDataToFile()
中完成,工作正常:
private void WriteAudioDataToFile()
{
byte[] data = new byte[bufferSize];
string filename = GetTempFilename();
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filename);
}
catch (Java.IO.FileNotFoundException e)
{
}
int read = 0;
if (null != fos)
{
while (isRecording)
{
read = audioRecord.Read(data, 0, bufferSize);
if ((int)RecordStatus.ErrorInvalidOperation != read)
{
try
{
fos.Write(data);
}
catch (Java.IO.IOException e)
{
}
}
}
try
{
fos.Close();
}
catch (Java.IO.IOException e)
{
}
}
}
写入文件后,我想执行其他任务:
void OnNext()
{
short[] audioBuffer = new short[2048];
audioRecord.Read(audioBuffer, 0, audioBuffer.Length);
int[] result = new int[audioBuffer.Length];
for (int i = 0; i < audioBuffer.Length; i++)
{
result[i] = (int)audioBuffer[i];
}
samplesUpdated(this, new SamplesUpdatedEventArgs(result));
}
但由于我需要将文件写入和其他任务结合起来,我尝试在文件写入后移动OnNext()
方法:
private void WriteAudioDataToFile()
{
//...
try
{
fos.Write(data);
short[] dataShort = new short[bufferSize];
dataShort = Array.ConvertAll(data, d => (short)d);
int[] result = new int[dataShort.Length];
for (int i = 0; i < dataShort.Length; i++)
{
result[i] = (int)dataShort[i];
}
samplesUpdated(this, new SamplesUpdatedEventArgs(result));
}
catch (Java.IO.IOException e)
{
}
//...
}
private void writeaudiodata文件()
{
//...
尝试
{
写入(数据);
short[]dataShort=新的short[bufferSize];
dataShort=Array.ConvertAll(data,d=>(short)d);
int[]结果=新的int[dataShort.Length];
对于(int i=0;i
但是这根本不符合预期:
- 录制的文件似乎“已损坏”:当我听到它时,声音“加速”
- 我得到的光谱图的值不正确:问题似乎来自
到字节[]
的转换短[]
- 我需要使用
写入文件:byte[]
fos.Write(数据)代码>
- 我需要使用
执行其他任务short[]
- 使用相同的录音创建第二个线程以显示频谱图
- 使用另一个录音创建第二个线程以显示频谱图
private void WriteAudioDataToFile()
{
//...
try
{
fos.Write(data);
short[] dataShort = new short[bufferSize];
dataShort = Array.ConvertAll(data, d => (short)d);
int[] result = new int[dataShort.Length];
for (int i = 0; i < dataShort.Length; i++)
{
result[i] = (int)dataShort[i];
}
samplesUpdated(this, new SamplesUpdatedEventArgs(result));
}
catch (Java.IO.IOException e)
{
}
//...
}