3

Using C++ 11 in Visual Studio 2012, I'm trying to sounds which I've observed in Pascal. In Pascal, it seems like you're able to send a frequency to the internal speaker, which plays this frequency until you tell it to stop (or until you tell it to play a different frequency). So here's what I need:

  • I must be able to specify the frequency of the sound
  • The sound must have little or no gap (up to maybe 5ms would be acceptable)
  • I do not want to use external sound libraries (please do not waste my time by suggesting them, unless they are incredibly lightweight and provide an exceptionally wide range of use)
  • Preferably, the sound would be played on internal speaker, rather than through the computer's regular speakers

I can't find any include-able libraries/headers in visual studio which provide the ability to send a waveform to the internal speaker. I'm willing to try to work directly with the internal speaker (I know this would be hard, but I'm not an idiot - I think I can figure it out, with some guidance), but I can't find any documentation on accessing the internal speaker in Windows.

EDIT: From this post, I was able to gather that most computers nowadays don't actually have an internal speaker. Bummer. That's fine though - I can use the connected speakers, but I still have the following requirements:

  • I need to be able to specify a frequency and have the speakers play that frequency until I tell them to stop
  • I would rather not use external libraries

EDIT 2: Here's the class I'm working on:

#define HALF_NOTE 1.059463094359 // HALF_NOTE ^ 12 = 2

#include <Windows.h>
#include <math.h>

class SoundEffect
{
public:
    SoundEffect(){}

    void Play()
    {
        for (int i = 0; data[i + 1] > 0; i++)
        {
            Beep(16 * pow(HALF_NOTE, data[i++] - 1), data[i] * 10); // (frequency of c0) * (twelfth root of 2) ^ (number of half steps above c0)

            // Ideally, the code would look more like this (pseudocode):
            // sound(16 * pow(HALF_NOTE, data[i++] - 1)); // Start playing the specified frequency
            // delay(data[i] * 10);
        }
        // nosound();
    }

    int& operator[] (int location) { return data[location]; }

private:
    int data[256];
};
4

2 回答 2

1

我最终使用 Windows 多媒体 API 创建波形并将它们发送到声音设备。我的解决方案基于此处的教程。这就是我最终得到的结果:

#define HALF_NOTE 1.059463094359 // HALF_NOTE ^ 12 = 2
#define PI 3.14159265358979

#include <Windows.h>
#include <math.h>
using namespace std;

class SoundEffect
{
public:
    SoundEffect()
    {
        m_data = NULL;
    }
    SoundEffect(const int noteInfo[], const int arraySize)
    {
        // Initialize the sound format we will request from sound card
        m_waveFormat.wFormatTag = WAVE_FORMAT_PCM;     // Uncompressed sound format
        m_waveFormat.nChannels = 1;                    // 1 = Mono, 2 = Stereo
        m_waveFormat.wBitsPerSample = 8;               // Bits per sample per channel
        m_waveFormat.nSamplesPerSec = 11025;           // Sample Per Second
        m_waveFormat.nBlockAlign = m_waveFormat.nChannels * m_waveFormat.wBitsPerSample / 8;
        m_waveFormat.nAvgBytesPerSec = m_waveFormat.nSamplesPerSec * m_waveFormat.nBlockAlign;
        m_waveFormat.cbSize = 0;

        int dataLength = 0, moment = (m_waveFormat.nSamplesPerSec / 75);
        double period = 2.0 * PI / (double) m_waveFormat.nSamplesPerSec;

        // Calculate how long we need the sound buffer to be
        for (int i = 1; i < arraySize; i += 2)
            dataLength += (noteInfo[i] != 0) ? noteInfo[i] * moment : moment;

        // Allocate the array
        m_data = new char[m_bufferSize = dataLength];

        int placeInData = 0;

        // Make the sound buffer
        for (int i = 0; i < arraySize; i += 2)
        {
            int relativePlaceInData = placeInData;

            while ((relativePlaceInData - placeInData) < ((noteInfo[i + 1] != 0) ? noteInfo[i + 1] * moment : moment))
            {
                // Generate the sound wave (as a sinusoid)
                // - x will have a range of -1 to +1
                double x = sin((relativePlaceInData - placeInData) * 55 * pow(HALF_NOTE, noteInfo[i]) * period);

                // Scale x to a range of 0-255 (signed char) for 8 bit sound reproduction
                m_data[relativePlaceInData] = (char) (127 * x + 128);

                relativePlaceInData++;
            }

            placeInData = relativePlaceInData;
        }
    }
    SoundEffect(SoundEffect& otherInstance)
    {
        m_bufferSize = otherInstance.m_bufferSize;
        m_waveFormat = otherInstance.m_waveFormat;

        if (m_bufferSize > 0)
        {
            m_data = new char[m_bufferSize];

            for (int i = 0; i < otherInstance.m_bufferSize; i++)
                m_data[i] = otherInstance.m_data[i];
        }
    }
    ~SoundEffect()
    {
        if (m_bufferSize > 0)
            delete [] m_data;
    }

    SoundEffect& operator=(SoundEffect& otherInstance)
    {
        if (m_bufferSize > 0)
            delete [] m_data;

        m_bufferSize = otherInstance.m_bufferSize;
        m_waveFormat = otherInstance.m_waveFormat;

        if (m_bufferSize > 0)
        {
            m_data = new char[m_bufferSize];

            for (int i = 0; i < otherInstance.m_bufferSize; i++)
                m_data[i] = otherInstance.m_data[i];
        }

        return *this;
    }

    void Play()
    {
        // Create our "Sound is Done" event
        m_done = CreateEvent (0, FALSE, FALSE, 0);

        // Open the audio device
        if (waveOutOpen(&m_waveOut, 0, &m_waveFormat, (DWORD) m_done, 0, CALLBACK_EVENT) != MMSYSERR_NOERROR) 
        {
            cout << "Sound card cannot be opened." << endl;
            return;
        }

        // Create the wave header for our sound buffer
        m_waveHeader.lpData = m_data;
        m_waveHeader.dwBufferLength = m_bufferSize;
        m_waveHeader.dwFlags = 0;
        m_waveHeader.dwLoops = 0;

        // Prepare the header for playback on sound card
        if (waveOutPrepareHeader(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            cout << "Error preparing Header!" << endl;
            return;
        }

        // Play the sound!
        ResetEvent(m_done); // Reset our Event so it is non-signaled, it will be signaled again with buffer finished

        if (waveOutWrite(m_waveOut, &m_waveHeader, sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            cout << "Error writing to sound card!" << endl;
            return;
        }

        // Wait until sound finishes playing
        if (WaitForSingleObject(m_done, INFINITE) != WAIT_OBJECT_0)
        {
            cout << "Error waiting for sound to finish" << endl;
            return;
        }

        // Unprepare our wav header
        if (waveOutUnprepareHeader(m_waveOut, &m_waveHeader,sizeof(m_waveHeader)) != MMSYSERR_NOERROR)
        {
            cout << "Error unpreparing header!" << endl;
            return;
        }

        // Close the wav device
        if (waveOutClose(m_waveOut) != MMSYSERR_NOERROR)
        {
            cout << "Sound card cannot be closed!" << endl;
            return;
        }

        // Release our event handle
        CloseHandle(m_done);
    }

private:
    HWAVEOUT m_waveOut; // Handle to sound card output
    WAVEFORMATEX m_waveFormat; // The sound format
    WAVEHDR m_waveHeader; // WAVE header for our sound data
    HANDLE m_done; // Event Handle that tells us the sound has finished being played.
                   // This is a very efficient way to put the program to sleep
                   // while the sound card is processing the sound buffer

    char* m_data; // Sound data buffer
    int m_bufferSize; // Size of sound data buffer
};

相当复杂,但它有效。我将它与这样的文本文件一起使用(DOS mario & luigi 的音效):

LifeMusic 56 8 61 8 65 8 61 8 63 8 68 8
GrowMusic 37 4 44 4 49 4 38 4 45 4 50 4 39 4 46 4 51 4
CoinMusic 66 1
PipeMusic 13 0 13 8 1 0 1 16 13 0 13 8 1 0 1 16 13 0 13 8 1 0 1 16
FireMusic 41 1 46 1
HitMusic 25 2 13 3 1 4 25 1 13 2 1 3
DeadMusic 25 3 13 4 1 6
NoteMusic 1 3 13 4 1 6
StarMusic 37 4 41 4 44 4 49 4 53 4 56 4 61 4 65 4 68 4 73 4

为了简要概述,我的主文件在这些行中读取。对于每一行,它从一个整数数组创建一个音效,并创建一个映射,其中键是音效的名称,值是创建的SoundEffect实例。

在文本文件中,每一行应该有偶数个整数。如果将单行整数分成两对,第一个数字将是 A1 上方的半步数(以确定频率),第二个数字将是持续时间,以 75 秒为单位(任意,I知道)。

于 2013-11-11T06:42:36.590 回答
1

不久前,我搜索了类似的东西(生成简单的声音),并找到了可以完成这项工作的这些库:

不过,我还没有时间尝试比较它们。玩得开心:)

于 2013-11-10T20:02:06.727 回答