gpt4 book ai didi

c# - Xamarin:播放声音一分钟

转载 作者:行者123 更新时间:2023-12-03 02:09:46 25 4
gpt4 key购买 nike

我正在尝试播放一分钟的声音。我可以做到,但是我这样做的方式是先生成声音缓冲区然后播放它,这花费了太多时间,延迟很大。所以现在我正在尝试在播放声音时生成声音缓冲区,因此不会有延迟。它会播放约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时会抛出运行时错误:
在未初始化的AudioTrack上调用play()。

那我在做什么错呢?

最佳答案

这是我如何基于android示例在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`。

关于c# - Xamarin:播放声音一分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25273296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com