Показать полную графическую версию : Генератор сигналов на основе звуковой карты (Bass.Net)
tumanovalex
15-05-2021, 22:37
Хотел бы создать генератор сигналов различной формы (в том числе и сигналов постоянного уровня). Мне нужно просто выводить сигнал на выход звуковой карты, без записи сигналов в файл и его воспроизведения из файла. Я попробовал сделать так:int sample = Bass.BASS_SampleCreate(256, 440 * 64, 1, 1, BASSFlag.BASS_SAMPLE_LOOP | BASSFlag.BASS_SAMPLE_OVER_POS);
if (sample == 0)
ShowMes("Error SampleCreate");
short[] data = new short[128]; // data buffer
for (int i = 0; i < 1024; i++)
data[i] = (short)(32767.0 * Math.Sin(i * 6.283185 / 64)); // sine wave
if(!Bass.BASS_SampleSetData(sample, data))
ShowMes("Error SampleSetData");
А как запустить воспроизведение звука? Проект прикрепил.
А в комплекте bass.chm файлик был?
Creates a new sample.
HSAMPLE BASS_SampleCreate(
DWORD length,
DWORD freq,
DWORD chans,
DWORD max,
DWORD flags
);
Parameters
length The sample's length, in bytes.
freq The default sample rate.
chans The number of channels... 1 = mono, 2 = stereo, etc.
max Maximum number of simultaneous playbacks... 1 (min) - 65535 (max)... use one of the BASS_SAMPLE_OVER flags to choose the override decider, in the case of there being no free channel available for playback (ie. the sample is already playing max times).
flags A combination of these flags.
BASS_SAMPLE_8BITS Use 8-bit resolution. If neither this or the BASS_SAMPLE_FLOAT flags are specified, then the sample is 16-bit.
BASS_SAMPLE_FLOAT Use 32-bit floating-point sample data. Not really recommended for samples as it (at least) doubles the memory usage.
BASS_SAMPLE_LOOP Looped? Note that only complete sample loops are allowed; you cannot loop just a part of the sample. More fancy looping can be achieved via streaming.
BASS_SAMPLE_SOFTWARE Force the sample to not use hardware DirecSound mixing.
BASS_SAMPLE_VAM Enables the DX7 voice allocation and management features on the sample, which allows the sample to be played in software or hardware. This flag is ignored if the BASS_SAMPLE_SOFTWARE flag is also specified.
BASS_SAMPLE_3D Enable 3D functionality. This requires that the BASS_DEVICE_3D flag was specified when calling BASS_Init, and the sample must be mono (chans=1).
BASS_SAMPLE_MUTEMAX Mute the sample when it is at (or beyond) its max distance (software-mixed 3D samples only).
BASS_SAMPLE_OVER_VOL Override: the channel with the lowest volume is overridden.
BASS_SAMPLE_OVER_POS Override: the longest playing channel is overridden.
BASS_SAMPLE_OVER_DIST Override: the channel furthest away (from the listener) is overridden (3D samples only).
Return value
If successful, the new sample's handle is returned, else 0 is returned. Use BASS_ErrorGetCode to get the error code.
Error codes
BASS_ERROR_INIT BASS_Init has not been successfully called.
BASS_ERROR_ILLPARAM max is invalid.
BASS_ERROR_FORMAT The sample format is not supported by the device/drivers.
BASS_ERROR_MEM There is insufficient memory.
BASS_ERROR_NO3D Could not initialize 3D support.
BASS_ERROR_UNKNOWN Some other mystery problem!
Remarks
The sample's initial content is undefined. BASS_SampleSetData should be used to set the sample's data.
Unless the BASS_SAMPLE_SOFTWARE flag is used, the sample will use hardware mixing if hardware resources are available. Use BASS_GetInfo to see if there are hardware mixing resources available, and which sample formats are supported by the hardware. The BASS_SAMPLE_VAM flag allows a sample to be played by both hardware and software, with the decision made when the sample is played rather than when it is loaded. A sample's VAM options are set via BASS_SampleSetInfo.
To play a sample, first a channel must be obtained using BASS_SampleGetChannel, which can then be played using BASS_ChannelPlay.
If you want to play a large or one-off sample, then it would probably be better to stream it instead with BASS_StreamCreate.
Platform-specific
The BASS_SAMPLE_VAM flag is only available when using DirectSound output on Windows and requires DirectX 7 (or above).
Example
Create a 440 Hz sine wave sample.
HSAMPLE sample = BASS_SampleCreate(256, 440 * 64, 1, 1, BASS_SAMPLE_LOOP | BASS_SAMPLE_OVER_POS); // create sample
short data[128]; // data buffer
int a;
for (a = 0; a < 128; a++)
data[a] = (short)(32767.0 * sin(a * 6.283185 / 64)); // sine wave
BASS_SampleSetData(sample, data); // set the sample's data
Перевод интересующей строки:
Чтобы воспроизвести семпл, сначала необходимо получить канал с помощью BASS_SampleGetChannel, который затем можно воспроизвести с помощью BASS_ChannelPlay.
tumanovalex
16-05-2021, 16:28
Спасибо большое, файл справки есть, но невнимательно прочитал.
tumanovalex
17-05-2021, 16:17
Возникли еще вопросы.
1. На хабре приведена такая форма расчета для синуса:
float samplerate; // частота сэмпла
float wavefrequency; // частота волны
float wavevolume; // громкость волны
float period=samplerate/wavefrequency/2; //вычисляем период волны
float pi=3.14; //число pi
int n;
for(int a=0;a<samplelenght;a++) //устанавливаем цикл на длину сэмпла
{
n=wavevolume*sin(a*pi/period); //вычисление sine-волны
buffer[a]=n; //заносим вычисленное значение в буфер
}В примере по Bass какой параметр равен 64? Если я вставляю 64 как samplerate в формулу на хабре, то звук в динамике по частоте сильно отличается от того, который я слышу при использовании формулы из справки по Bass.
2. Почему длина семпла 256, а размер буфера 128?
Помогите, пожалуйста, разобраться, первый раз пытаюсь создать звук на ПК
© OSzone.net 2001-2012
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.