Last active
November 10, 2018 21:06
-
-
Save matkatmusic/2079936f7f2066077b3f42554208d2f4 to your computer and use it in GitHub Desktop.
Simple sinewave generator/writer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
replace your initialize() in your juce GUI project with this | |
*/ | |
void initialise (const String& commandLine) override | |
{ | |
// This method is where you should put your application's initialisation code.. | |
/* | |
we're going to write a 2-second long 16-bit wave file to disk. | |
*/ | |
MemoryBlock block(44100 * 2 * sizeof(uint16), true); | |
AudioBuffer<float> buffer(1, static_cast<int>(block.getSize() / sizeof(uint16))); | |
AudioDataConverters::convertInt16LEToFloat(block.getData(), | |
buffer.getWritePointer(0), | |
buffer.getNumSamples()); | |
//write a 440hz sinewave to the buffer | |
auto* writePointer = buffer.getWritePointer(0); | |
struct SineState | |
{ | |
float currentSampleRate = 44100.f; | |
float currentAngle = 0.f; | |
float cyclesPerSample = 440.f / currentSampleRate; | |
float angleDelta = cyclesPerSample * MathConstants<float>::twoPi; | |
}; | |
SineState sineState; | |
for( int i = 0; i < buffer.getNumSamples(); ++i ) | |
{ | |
auto currentSample = static_cast<float>(std::sin(sineState.currentAngle)); | |
sineState.currentAngle += sineState.angleDelta; //fine if it wrapps around | |
writePointer[i] = currentSample * 0.5f; | |
} | |
//save the buffer to disk | |
File audioFile (File::getSpecialLocation(File::SpecialLocationType::currentApplicationFile).getSiblingFile("test").withFileExtension(".aiff")); | |
audioFile.deleteFile(); | |
audioFile.create(); | |
if( audioFile.existsAsFile() ) | |
{ | |
ScopedPointer<FileOutputStream> fos(audioFile.createOutputStream()); | |
if( fos->openedOk() ) | |
{ | |
AiffAudioFormat aiff; | |
ScopedPointer<AudioFormatWriter> writer(aiff.createWriterFor(fos.get(), | |
44100, | |
1, | |
16, | |
{}, | |
0)); | |
if( writer != nullptr ) | |
{ | |
fos.release(); | |
if( writer->writeFromAudioSampleBuffer(buffer, 0, buffer.getNumSamples()) ) | |
{ | |
audioFile.revealToUser(); | |
} | |
else | |
{ | |
jassertfalse; //failed to write | |
} | |
} | |
else | |
{ | |
jassertfalse; //failed to create writer | |
} | |
} | |
} | |
jassertfalse; //go ahead and check your audio file in your DAW. | |
mainWindow = new MainWindow (getApplicationName()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment