int GMSynthDLL::ThreadProc() { if (live) { if (seqMode & seqPlay) ldTm = 0.02; else ldTm = 0.20; OpenWaveDevice(); inmgr.SetWaveOut(&wvd); } else { if (wvf.OpenWaveFile(outFileName, 2)) { OnEvent(SEQEVT_SEQSTOP, NULL); return GMSYNTH_ERR_FILEOPEN; } inmgr.SetWaveOut(&wvf); } inmgr.Reset(); seq.SequenceMulti(inmgr, stTime, endTime, seqMode); if (live) { bsInt32 drain = (bsInt32) (synthParams.sampleRate * (ldTm * 4)); while (--drain > 0) inmgr.Tick(); CloseWaveDevice(); } else wvf.CloseWaveFile(); return GMSYNTH_NOERROR; }
void FaceController::Speak(WaveFile &wave) { m_visemes.clear(); //Calculate which visemes to use from the wave file data float soundLength = wave.GetLength(); float maxAmp = wave.GetMaxAmplitude() * 0.3f; for (float i=0.0f; i<soundLength; i += 0.1f) { short amp = wave.GetAverageAmplitude(i, i + 0.1f); float p = min(amp / maxAmp, 1.0f); if (p < 0.2f) { m_visemes.push_back(Viseme(0, 0.0f, i)); } else if (p < 0.4f) { float prc = max((p - 0.2f) / 0.2f, 0.3f); m_visemes.push_back(Viseme(3, prc, i)); } else if (p < 0.7f) { float prc = max((p - 0.4f) / 0.3f, 0.3f); m_visemes.push_back(Viseme(1, prc, i)); } else { float prc = max((p - 0.7f) / 0.3f, 0.3f); m_visemes.push_back(Viseme(4, prc, i)); } } m_visemeIndex = 1; m_speechTime = 0.0f; }
LRESULT CMainDlg::OnSaveWave(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { char fileName[MAX_PATH]; memset(fileName, 0, sizeof(fileName)); OPENFILENAME ofn; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hWnd; ofn.lpstrFilter = "Sound Files(*.wav)\0*.wav\0All Files(*.*)\0*.*\0"; ofn.nFilterIndex = 1; ofn.lpstrFile = fileName; ofn.lpstrDefExt = ".wav"; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_OVERWRITEPROMPT; if (GetSaveFileName (&ofn)) { double frq = GetFrequency(); GenWaveI wv; wv.InitWT(frq, WT_USR(0)); EnvGen eg; eg.InitEG(1.0, 2.0, 0.05, 0.05); WaveFile wvf; wvf.OpenWaveFile(fileName, 2); long totalSamples = (long) (2.0 * synthParams.sampleRate); for (long n = 0; n < totalSamples; n++) wvf.Output1(eg.Gen() * wv.Gen()); wvf.CloseWaveFile(); } return 0; }
bool MonoRecorder::Save(const std::string& fn, bool norm, float norm_max) { WaveFile w; const RecorderTrack& to_save = *(save_processed ? processed_tracks[0] : tracks[0]); w.FromFloat(&to_save[0],to_save.getLength(),norm,norm_max); w.Save(fn.c_str()); return true; }
bool StereoRecorder::Save(const std::string& fn, bool norm, float norm_max) { WaveFile w; const RecorderTrack& left = *(save_processed ? processed_tracks[0] : tracks[0]); const RecorderTrack& right = *(save_processed ? processed_tracks[1] : tracks[1]); w.FromFloat(&left[0],&right[0],left.getLength(),right.getLength(),norm); w.Save(fn.c_str()); return true; }
int main(void) { WaveFile myFile; myFile.loadWave("DAFT.wav"); WaveFIR::LPF(myFile, 100, 100, 0, myFile.length-1); //myFile.normalize(); myFile.saveWave("TEST.wav"); return 0; }
// Destroy BOOL AudioStream::Destroy (void) { BOOL fRtn = SUCCESS; EnterCriticalSection(&write_lock); // Stop playback Stop (); // Release DirectSound buffer if (m_pdsb) { m_pdsb->Release (); m_pdsb = NULL; Snd_sram -= m_cbBufSize; } // Delete WaveFile object if (m_pwavefile) { m_pwavefile->Close(); free(m_pwavefile); m_pwavefile = NULL; } status = ASF_FREE; LeaveCriticalSection(&write_lock); return fRtn; }
// Cue void AudioStream::Cue (void) { UINT num_bytes_written; if (!m_fCued) { m_bFade = FALSE; m_fade_timer_id = 0; m_finished_id = 0; m_bPastLimit = FALSE; m_lVolume = 0; m_lCutoffVolume = -10000; m_bDestroy_when_faded = FALSE; // Reset buffer ptr m_cbBufOffset = 0; // Reset file ptr, etc m_pwavefile->Cue (); // Reset DirectSound buffer m_pdsb->SetCurrentPosition (0); // Fill buffer with wave data WriteWaveData (m_cbBufSize, &num_bytes_written,0); m_fCued = TRUE; } }
// Destroy BOOL AudioStream::Destroy(void) { BOOL fRtn = SUCCESS; ENTER_CRITICAL_SECTION(write_lock); // Stop playback Stop(); // Release DirectSound buffer if (m_pdsb) { m_pdsb->Release(); m_pdsb = NULL; Snd_sram -= m_cbBufSize; } // Delete WaveFile object if (m_pwavefile) { m_pwavefile->Close(); vm_free(m_pwavefile); m_pwavefile = NULL; } status = ASF_FREE; LEAVE_CRITICAL_SECTION(write_lock); return fRtn; }
LRESULT CMainDlg::OnSave(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { char fileName[MAX_PATH]; memset(fileName, 0, sizeof(fileName)); OPENFILENAME ofn; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hWnd; ofn.lpstrFilter = "Sound Files(*.wav)\0*.wav\0All Files(*.*)\0*.*\0"; ofn.nFilterIndex = 1; ofn.lpstrFile = fileName; ofn.lpstrDefExt = ".wav"; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_OVERWRITEPROMPT; if (GetSaveFileName (&ofn)) { WaveFile wvf; wvf.OpenWaveFile(fileName, 2); InitGen(); long totalSamples = (long) ((durTotal * synthParams.sampleRate) + 0.5); long atkSamples = (long) (durAtkSus * synthParams.sampleRate); long n; for (n = 0; n < atkSamples; n++) wvf.Output1(Generate()); NoteOff(); while (n++ < totalSamples) wvf.Output1(Generate()); for (n = 0; n < 440; n++) wvf.Output1(0); wvf.CloseWaveFile(); } return 0; }
bool WaveFile::CopyFrom(WaveFile& other) { const size_t transferBufSize = 4096; if (!writeFile) { error = "Copy to an unopened file"; return false; } else if (!other.readFile) { error = "Copy from an unopened file"; return false; } try { // allocate the transfer buffer char* transferBuffer = new char[transferBufSize]; unsigned long bytesRead = 0; try { if (!other.ResetToStart()) throw error = "Couldn't reset input file to start"; while (bytesRead < other.dataLength) { // calculate the size of the next buffer size_t bytesToRead = (size_t) min(transferBufSize, size_t(other.dataLength - bytesRead)); // read the buffer if (fread(transferBuffer, 1, bytesToRead, other.readFile->filep()) != bytesToRead) throw error = "Error reading samples from input file"; bytesRead += bytesToRead; // write the buffer if (fwrite(transferBuffer, 1, bytesToRead, writeFile) != bytesToRead) throw error = "Error writing samples to output file"; dataLength += bytesToRead; changed = true; } // delete the transfer buffer delete[] transferBuffer; } catch (...) { delete[] transferBuffer; throw error; } } catch (...) { return false; } return true; }
// WriteSilence // // Writes silence to sound buffer. This is a helper method used by // ServiceBuffer; it's not exposed to users of the AudioStream class. BOOL AudioStream::WriteSilence(UINT size) { HRESULT hr; LPBYTE lpbuf1 = NULL; LPBYTE lpbuf2 = NULL; DWORD dwsize1 = 0; DWORD dwsize2 = 0; DWORD dwbyteswritten1 = 0; DWORD dwbyteswritten2 = 0; BOOL fRtn = SUCCESS; // Lock the sound buffer hr = m_pdsb->Lock(m_cbBufOffset, size, (void**)(&lpbuf1), &dwsize1, (void**)(&lpbuf2), &dwsize2, 0); if (hr == DS_OK) { // Get silence data for this file format. Although word sizes vary for different // wave file formats, ::Lock will always return pointers on word boundaries. // Because silence data for 16-bit PCM formats is 0x0000 or 0x00000000, we can // get away with writing bytes and ignoring word size here. BYTE bSilence = m_pwavefile->GetSilenceData(); // Write silence to sound buffer. Because the sound buffer is circular, we may have to // do two write operations if locked portion of buffer wraps around to start of buffer. memset(lpbuf1, bSilence, dwsize1); dwbyteswritten1 = dwsize1; // Second write required? if (lpbuf2) { memset(lpbuf2, bSilence, dwsize2); dwbyteswritten2 = dwsize2; } // Update our buffer offset and unlock sound buffer m_cbBufOffset = (m_cbBufOffset + dwbyteswritten1 + dwbyteswritten2) % m_cbBufSize; // m_pdsb->Unlock (lpbuf1, dwbyteswritten1, lpbuf2, dwbyteswritten2); m_pdsb->Unlock(lpbuf1, dwsize1, lpbuf2, dwsize2); } else { // Error locking sound buffer nprintf(("SOUND", "SOUND ==> Error, unable to lock sound buffer in AudioStr\n")); fRtn = FAILURE; } return (fRtn); }
static void ShowErrors(WaveFile& from, WaveFile& to) { bool any = from.GetError() || to.GetError(); if (from.GetError()) cout << "Error on input: " << from.GetError() << "." << endl; if (to.GetError()) cout << "Error on output: " << to.GetError() << "." << endl; if (!any) cout << "Success." << endl; }
AmpValue Generate(float duration, GenUnit *wv, EnvGen *eg, AmpValue in = 1.0) { long totalSamples = (long) ((duration * synthParams.sampleRate) + 0.5); AmpValue volume; AmpValue value; AmpValue peak = 0.0; eg->Reset(); for (long n = 0; n < totalSamples; n++) { volume = eg->Gen(); value = wv->Sample(in); if (value > peak) peak = value; wvf.Output1(value * volume); } return peak; }
void GenerateVib(FrqValue duration, GenWave *wv, EnvGen *eg, AmpValue lfoAmp) { GenWave32 lfo; lfo.InitWT(3.5, WT_SIN); long totalSamples = (long) ((duration * synthParams.sampleRate) + 0.5); AmpValue volume; AmpValue value; eg->Reset(); for (long n = 0; n < totalSamples; n++) { volume = eg->Gen(); wv->Modulate(lfoAmp * lfo.Gen()); value = wv->Sample(1.0); wvf.Output1(value * volume); } }
GMSynthDLL(Opaque w) { magic = GMSYNTH_MAGIC; sbnk = 0; seqMode = seqOff; seq.SetMaxNotes(32); kbd.SetSequenceInfo(&seq, &inmgr); wvf.SetBufSize(30); ldTm = 0.5; live = 1; stTime = 0; endTime = 0; #ifdef _WIN32 SetWaveDevice(NULL); wavWnd = (HWND)w; #endif #ifdef UNIX SetWaveDevice((void*)"hw:0"); #endif }
// 初期化 void initialize() { // デフォルトのKinectを取得する ERROR_CHECK( ::GetDefaultKinectSensor( &kinect ) ); ERROR_CHECK( kinect->Open() ); // オーディオを開く CComPtr<IAudioSource> audioSource; ERROR_CHECK( kinect->get_AudioSource( &audioSource ) ); // オーディオビームリーダーを開く ERROR_CHECK( audioSource->OpenReader( &audioBeamFrameReader ) ); // データバッファを作成する UINT subFrameLength = 0; ERROR_CHECK( audioSource->get_SubFrameLengthInBytes( &subFrameLength ) ); audioBuffer.resize( subFrameLength ); // Waveファイルを設定する audioFile.Open( "KinectAudio.wav" ); }
int main(int , char **) { WaveFile wf; wf.SetupFormat(); if (!wf.OpenWrite("A440.wav")) { cout << "Can't open for writing: " << wf.GetError(); return 1; } const dataLength = 1 /*sec*/ * wf.GetSampleRate(); // in samples float alpha = 0; for (int i = 0; i < dataLength; i++) { wf.WriteSample(sin(alpha) / 2); alpha += 2 * M_PI * frequency / wf.GetSampleRate(); } return 0; }
// オーディオフレームの更新 void updateAudioFrame() { // ビームフレームリストを取得する CComPtr<IAudioBeamFrameList> audioBeamFrameList; auto ret = audioBeamFrameReader->AcquireLatestBeamFrames( &audioBeamFrameList ); if ( ret != S_OK ) { return; } // ビームフレームを取得する UINT beamCount = 0; ERROR_CHECK( audioBeamFrameList->get_BeamCount( &beamCount ) ); for ( int i = 0; i < beamCount; ++i ) { CComPtr<IAudioBeamFrame> audioBeamFrame; ERROR_CHECK( audioBeamFrameList->OpenAudioBeamFrame( i, &audioBeamFrame ) ); // サブフレームを取得する UINT subFrameCount = 0; ERROR_CHECK( audioBeamFrame->get_SubFrameCount( &subFrameCount ) ); for ( int j = 0; j < subFrameCount; ++j ) { CComPtr<IAudioBeamSubFrame> audioBeamSubFrame; ERROR_CHECK( audioBeamFrame->GetSubFrame( j, &audioBeamSubFrame ) ); audioBeamSubFrame->CopyFrameDataToArray( audioBuffer.size(), &audioBuffer[0] ); // 音声データを書き込む audioFile.Write( &audioBuffer[0], audioBuffer.size() ); } } }
static void ShowFormat(WaveFile& wave, bool details = true) { cout << "Format: " << wave.GetFormatType() << (wave.IsCompressed()? " (compressed)" : " (PCM)") << endl << "Channels: " << wave.GetNumChannels() << endl << "Sample rate: " << wave.GetSampleRate() << endl << "Bytes per second: " << wave.GetBytesPerSecond() << endl << "Bytes per sample: " << wave.GetBytesPerSample() << endl << "Bits per channel: " << wave.GetBitsPerChannel() << endl << "Bytes: " << wave.GetDataLength() << endl << "Samples: " << wave.GetNumSamples() << endl << "Seconds: " << wave.GetNumSeconds() << endl; if(wave.GetFile()) cout << "File pointer: " << ftell(wave.GetFile()) << endl; else cout << "File pointer: null" << endl; if (details) { string type, value; if (wave.GetFirstExtraItem(type, value)) { cout << "Extra data:" << endl; do { cout << " " << type << ": " << value << endl; } while (wave.GetNextExtraItem(type, value)); } wave.ResetToStart(); } pause(); }
// WriteWaveData // // Writes wave data to sound buffer. This is a helper method used by Create and // ServiceBuffer; it's not exposed to users of the AudioStream class. BOOL AudioStream::WriteWaveData (UINT size, UINT *num_bytes_written, int service) { HRESULT hr; LPBYTE lpbuf1 = NULL; LPBYTE lpbuf2 = NULL; DWORD dwsize1 = 0; DWORD dwsize2 = 0; DWORD dwbyteswritten1 = 0; DWORD dwbyteswritten2 = 0; BOOL fRtn = SUCCESS; unsigned char *uncompressed_wave_data; *num_bytes_written = 0; if ( size == 0 || m_bReadingDone ) { return fRtn; } if ( !m_pdsb || !m_pwavefile ) { return fRtn; } if ( service ) { EnterCriticalSection(&Global_service_lock); } if ( service ) { uncompressed_wave_data = Wavedata_service_buffer; } else { uncompressed_wave_data = Wavedata_load_buffer; } int num_bytes_read = 0; // Lock the sound buffer hr = m_pdsb->Lock (m_cbBufOffset, size, (void**)(&lpbuf1), &dwsize1, (void**)(&lpbuf2), &dwsize2, 0); if (hr == DS_OK) { // Write data to sound buffer. Because the sound buffer is circular, we may have to // do two write operations if locked portion of buffer wraps around to start of buffer. Assert(lpbuf1); num_bytes_read = m_pwavefile->Read(uncompressed_wave_data, dwsize1+dwsize2,service); if ( num_bytes_read == -1 ) { // means nothing left to read! num_bytes_read = 0; m_bReadingDone = 1; } if ( num_bytes_read > 0 ) { if ( (unsigned int)num_bytes_read > dwsize1 ) { dwbyteswritten1 = dwsize1; dwbyteswritten2 = num_bytes_read - dwsize1; memcpy(lpbuf1, uncompressed_wave_data, dwsize1); Assert(lpbuf2); memcpy(lpbuf2, uncompressed_wave_data+dwsize1, num_bytes_read-dwsize1); } else { dwbyteswritten1 = num_bytes_read; dwbyteswritten2 = 0; memcpy(lpbuf1, uncompressed_wave_data, num_bytes_read); } } // Update our buffer offset and unlock sound buffer m_cbBufOffset = (m_cbBufOffset + dwbyteswritten1 + dwbyteswritten2) % m_cbBufSize; *num_bytes_written = dwbyteswritten1 + dwbyteswritten2; m_pdsb->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2); } else { // Error locking sound buffer nprintf(("SOUND", "SOUND ==> Error, unable to lock sound buffer in AudioStr\n")); fRtn = FAILURE; } if ( service ) { LeaveCriticalSection(&Global_service_lock); } return (fRtn); }
// Create BOOL AudioStream::Create (LPSTR pszFilename, AudioStreamServices * pass) { BOOL fRtn = SUCCESS; // assume success Assert(pszFilename); Assert(pass); m_pass = pass; Init_Data(); if (pszFilename && m_pass) { // Create a new WaveFile object m_pwavefile = (WaveFile *)malloc(sizeof(WaveFile)); Assert(m_pwavefile); if (m_pwavefile) { // Call constructor m_pwavefile->Init(); // Open given file m_pwavefile->m_bits_per_sample_uncompressed = m_bits_per_sample_uncompressed; if (m_pwavefile->Open (pszFilename)) { // Calculate sound buffer size in bytes // Buffer size is average data rate times length of buffer // No need for buffer to be larger than wave data though m_cbBufSize = (m_pwavefile->GetUncompressedAvgDataRate () * m_nBufLength) / 1000; nprintf(("SOUND", "SOUND => Stream buffer created using %d bytes\n", m_cbBufSize)); // m_cbBufSize = (m_cbBufSize > m_pwavefile->GetDataSize ()) ? m_pwavefile->GetDataSize () : m_cbBufSize; //nprintf(("Sound", "SOUND => average data rate = %d\n\r", m_pwavefile->GetUncompressedAvgDataRate ())); //nprintf(("Sound", "SOUND => m_cbBufSize = %d\n\r", m_cbBufSize)); // Create sound buffer HRESULT hr; memset (&m_dsbd, 0, sizeof (DSBUFFERDESC)); m_dsbd.dwSize = sizeof (DSBUFFERDESC); m_dsbd.dwBufferBytes = m_cbBufSize; m_dsbd.lpwfxFormat = &m_pwavefile->m_wfmt; m_dsbd.dwFlags = DSBCAPS_STATIC | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_LOCSOFTWARE; hr = (m_pass->GetPDS ())->CreateSoundBuffer (&m_dsbd, &m_pdsb, NULL); if (hr == DS_OK) { // Cue for playback Cue (); Snd_sram += m_cbBufSize; } else { // Error, unable to create DirectSound buffer nprintf(("Sound", "SOUND => Error, unable to create DirectSound buffer\n\r")); if (hr == DSERR_BADFORMAT) { nprintf(("Sound", "SOUND => Bad format (probably ADPCM)\n\r")); } fRtn = FAILURE; } } else { // Error opening file nprintf(("SOUND", "SOUND => Failed to open wave file: %s\n\r", pszFilename)); m_pwavefile->Close(); free(m_pwavefile); m_pwavefile = NULL; fRtn = FAILURE; } } else { // Error, unable to create WaveFile object nprintf(("Sound", "SOUND => Failed to create WaveFile object %s\n\r", pszFilename)); fRtn = FAILURE; } } else { // Error, passed invalid parms fRtn = FAILURE; } return (fRtn); }
int main(int argc, char *argv[]) { #if defined(USE_MSXML) CoInitialize(0); #endif const char *fname = "data.xml"; if (argc > 1) fname = argv[1]; InitSynthesizer(); mix.SetChannels(2); mix.MasterVolume(1.0, 1.0); mix.ChannelOn(0, 1); mix.ChannelOn(1, 1); mix.ChannelVolume(0, 1.0); mix.ChannelVolume(1, 1.0); #ifdef ADD_REVERB mix.SetFxChannels(1); mix.FxInit(0, &rvrb, 0.1); mix.FxLevel(0, 0, 0.2); mix.FxLevel(0, 1, 0.2); rvrb.InitReverb(1.0, 2.0); #endif inMgr.Init(&mix, &wvf); inMgr.AddType("Tone", ToneInstr::ToneFactory, ToneInstr::ToneEventFactory); inMgr.AddType("ToneFM", ToneFM::ToneFMFactory, ToneFM::ToneFMEventFactory); inMgr.AddType("AddSynth", AddSynth::AddSynthFactory, AddSynth::AddSynthEventFactory); inMgr.AddType("SubSynth", SubSynth::SubSynthFactory, SubSynth::SubSynthEventFactory); inMgr.AddType("FMSynth", FMSynth::FMSynthFactory, FMSynth::FMSynthEventFactory); inMgr.AddType("MatrixSynth", MatrixSynth::MatrixSynthFactory, MatrixSynth::MatrixSynthEventFactory); inMgr.AddType("WFSynth", WFSynth::WFSynthFactory, WFSynth::WFSynthEventFactory); inMgr.AddType("Chuffer", Chuffer::ChufferFactory, Chuffer::ChufferEventFactory); inMgr.AddType("ModSynth", ModSynth::ModSynthFactory, ModSynth::ModSynthEventFactory); inMgr.AddType("BuzzSynth", BuzzSynth::InstrFactory, BuzzSynth::EventFactory); InstrMapEntry *ime = 0; while ((ime = inMgr.EnumType(ime)) != 0) ime->dumpTmplt = DestroyTemplate; XmlSynthDoc doc; XmlSynthElem rootNode(&doc); if (!doc.Open(fname, &rootNode)) { printf("Cannot open file %s\n", fname); exit(1); } // Optional: use LoadInstrLib(inMgr, fname) // but we want to discover the inum values // and add sequences programaticaly... XmlSynthElem elem(&doc); XmlSynthElem *inst = rootNode.FirstChild(&elem); while (inst != NULL) { if (inst->TagMatch("instr")) { InstrConfig *ent = inMgr.LoadInstr(inst); if (strcmp(ent->instrType->GetType(), "WFSynth") == 0) AddEvent(ent->inum, 48, 1.0); else AddSequence(ent->inum, 0.25); } inst = elem.NextSibling(&elem); } doc.Close(); if (wvf.OpenWaveFile("example10.wav", 2)) { printf("Cannot open wavefile for output\n"); exit(1); } seq.Sequence(inMgr); #ifdef ADD_REVERB // drain the reverb... AmpValue lv; AmpValue rv; long n = synthParams.isampleRate; while (n-- > 0) { mix.Out(&lv, &rv); wvf.Output2(lv, rv); } #endif wvf.CloseWaveFile(); /////////////////////////////////////////////////////////////// // Code to test instrument save functions... #define TEST_SAVE_INSTR 1 #ifdef TEST_SAVE_INSTR doc.NewDoc("instrlib", &rootNode); InstrConfig *inc = inMgr.EnumInstr(0); while (inc) { InstrMapEntry *ime = inc->instrType; Instrument *ip = (Instrument *)inc->instrTmplt; if (ip) { rootNode.AddChild("instr", &elem); elem.SetAttribute("id", inc->inum); elem.SetAttribute("type", ime->itype); elem.SetAttribute("name", inc->GetName()); elem.SetAttribute("desc", inc->GetDesc()); ip->Save(&elem); } inc = inMgr.EnumInstr(inc); } bsString outxml(fname); bsString outbase; bsString outfile; outxml.SplitPath(outbase, outfile, 1); outxml = outbase; outxml += '_'; outxml += outfile; doc.Save(outxml); #endif /////////////////////////////////////////////////////////////// return 0; }
void Silence(float t) { long n = (long) (t * synthParams.sampleRate); while (n-- > 0) wvf.Output1(0); }
int main(int argc, char **argv) { // Parsing printf("%s\n%s\n", argv[0], argv[1]); char targetName[256]; strcpy(targetName, argv[0]); for(int n=strlen(targetName)-1; n>=0; --n) { if(targetName[n] != '\\') { targetName[n] = '\0'; } else { targetName[n] = '\0'; break; } } strcat(targetName, "\\Data\\Test.dat"); FILE *myFile = fopen(targetName, "wb"); WaveFile myWave; if(myFile == NULL) { printf("Something is wrong\n"); getchar(); fclose(myFile); return 0; } if(argc != 2) { printf("Drag a WavFile on this icon.\n"); getchar(); } else { myWave.loadWave(argv[1]); myWave.normalize(); printf("File Name : %s\n", argv[1]); int buffer; buffer = myWave.length; fwrite(&buffer, sizeof(int), 1, myFile); printf("Length : %d\n", buffer); if(ferror(myFile)) { printf("Something is wrong...\n"); } buffer = myWave.sample_rate; fwrite(&buffer, sizeof(int), 1, myFile); printf("Sample Rate : %d\n", buffer); for(int n=0; n<myWave.length; ++n) { if(myWave.data[0][n] >= 1.0) { buffer = int32_max - 1; } else if(myWave.data[0][n] < -1.0) { buffer = -int32_max; } else { buffer = int(int32_max*myWave.data[0][n]); } fwrite(&buffer, sizeof(int), 1, myFile); } printf("Done!\n"); } fclose(myFile); return 0; }
int main(int argc, char *argv[]) { InitSynthesizer(); long n; int pitch = 48; FrqValue duration = 2.75; AmpValue value1, value2; if (argc > 1) duration = atof(argv[1]); if (argc > 2) pitch = atoi(argv[2]); FrqValue frequency = synthParams.GetFrequency(pitch); if (wvf.OpenWaveFile("example07b.wav", 2)) { printf("Cannot open wavefile for output\n"); exit(1); } GenWaveFM wv; wv.InitFM(frequency, 1, 2, WT_SIN); EnvGen eg; eg.InitEG(0.5f, duration, 0.5f, 0.5f); long totalSamples = (long) ((duration * synthParams.sampleRate) + 0.5); // reference sound. for (n = 0; n < totalSamples; n++) { value2 = (eg.Gen() * wv.Gen()); wvf.Output1(value2); } Silence(0.25); // Flanger #1 varies from 0 to 5ms Flanger flng1; flng1.InitFlanger(0.5, 0.5, 0, 0.0025, 0.005, 0.15); // Flanger #2 varies from 45 to 50ms Flanger flng2; flng2.InitFlanger(0.5, 0.5, 0, 0.0042, 0.005, 0.15); // Flanger #3 is set for a chorus effect Flanger flng3; flng3.InitFlanger(0.5, 0.5, 0.5, 0.100, 0.001, 0.8); for (float snd = 0.5; snd <= 1; snd += 0.5) { wv.InitFM(frequency*snd, 1, 2, WT_SIN); eg.Reset(); flng1.Clear(); for (n = 0; n < totalSamples; n++) { value1 = (eg.Gen() * wv.Gen()); value2 = flng1.Sample(value1); wvf.Output2(value2, value2); } Silence(0.25); eg.Reset(); flng2.Clear(); for (n = 0; n < totalSamples; n++) { value1 = (eg.Gen() * wv.Gen()); value2 = flng2.Sample(value1); wvf.Output2(value2, value2); } Silence(0.25); eg.Reset(); flng3.Clear(); for (n = 0; n < totalSamples; n++) { value1 = (eg.Gen() * wv.Gen()); value2 = flng3.Sample(value1); wvf.Output2(value2, value2); } Silence(0.25); } wvf.CloseWaveFile(); return 0; }
void AudioDevice::PlayWaveFile(WaveFile &File, bool LoopForever) { #ifdef USE_DIRECTX_AUDIO if(_Device == NULL) { return; } RemoveVoices(true); if(_ActiveSourceVoices.Length() > 4) { return; } // Get format of wave file WAVEFORMATEX& pwfx = File.Format(); // Create the source voice IXAudio2SourceVoice* _SourceVoice; HRESULT hr = _Device->CreateSourceVoice( &_SourceVoice, &pwfx ); Assert(SUCCEEDED(hr), "CreateSourceVoice failed"); _ActiveSourceVoices.PushEnd(_SourceVoice); // Submit the wave sample data using an XAUDIO2_BUFFER structure XAUDIO2_BUFFER buffer = {0}; buffer.pAudioData = (BYTE *)File.Data().CArray(); buffer.Flags = XAUDIO2_END_OF_STREAM; // tell the source voice not to expect any data after this buffer buffer.AudioBytes = File.Data().Length();// * sizeof(DWORD); if(LoopForever) { buffer.LoopBegin = 1; buffer.LoopLength = 0; buffer.LoopCount = XAUDIO2_LOOP_INFINITE; } hr = _SourceVoice->SubmitSourceBuffer( &buffer ); Assert(SUCCEEDED(hr), "SubmitSourceBuffer failed"); hr = _SourceVoice->Start( 0 ); Assert(SUCCEEDED(hr), "SubmitSourceBuffer failed"); //delete[] pbWaveData; //Sleep(3000); //_SourceVoice->DestroyVoice(); // Let the sound play /*BOOL isRunning = TRUE; while( SUCCEEDED( hr ) && isRunning ) { XAUDIO2_VOICE_STATE state; pSourceVoice->GetState( &state ); isRunning = ( state.BuffersQueued > 0 ) != 0; // Wait till the escape key is pressed if( GetAsyncKeyState( VK_ESCAPE ) ) break; Sleep( 10 ); } // Wait till the escape key is released while( GetAsyncKeyState( VK_ESCAPE ) ) Sleep( 10 ); pSourceVoice->DestroyVoice(); SAFE_DELETE_ARRAY( pbWaveData ); return hr;*/ #endif }
int main(int argc, char *argv[]) { int pitch = 48; // middle C FrqValue duration = 1.0; AmpValue lfoAmp = 10; bsInt32 tl = 16384; if (argc > 1) duration = atof(argv[1]); if (argc > 2) pitch = atoi(argv[2]); if (argc > 3) tl = atol(argv[3]); InitSynthesizer(44100, tl); FrqValue frequency = synthParams.GetFrequency(pitch); if (wvf.OpenWaveFile("example04.wav", 1) < 0) { printf("Cannot open wavefile for output\n"); exit(1); } //EnvGen eg; EnvGenExp eg; //EnvGenLog eg; eg.SetBias(0.2); eg.InitEG(0.7, duration, 0.2, 0.3); GenWaveWT wv; GenWaveI wvi; GenWave32 wv32; //GenWave64 wv64; GenWaveFM wvfm; GenWaveAM wvam; GenWaveRM wvrm; ///////////////////////////////////////////////// // 1 - sine wave ///////////////////////////////////////////////// wv.InitWT(frequency, WT_SIN); Generate(duration, &wv, &eg); //GenerateVib(duration, &wv, &eg, lfoAmp); //GeneratePhaseVib(duration, &wv, &eg, lfoAmp); ///////////////////////////////////////////////// // 2 - sine wave using interpolation ///////////////////////////////////////////////// wvi.InitWT(frequency, WT_SIN); Generate(duration, &wvi, &eg); //GenerateVib(duration, &wvi, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvi, &eg, lfoAmp); Silence(0.25); ///////////////////////////////////////////////// // 3 - fixed summation of sine waves ///////////////////////////////////////////////// wv.InitWT(frequency, WT_SAW); Generate(duration, &wv, &eg); //GenerateVib(duration, &wv, &eg, lfoAmp); //GeneratePhaseVib(duration, &wv, &eg, lfoAmp); ///////////////////////////////////////////////// // 4 - fixed summation of sine waves using interpolation ///////////////////////////////////////////////// wvi.InitWT(frequency, WT_SAW); Generate(duration, &wvi, &eg); //GenerateVib(duration, &wvi, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvi, &eg, lfoAmp); ///////////////////////////////////////////////// // 5 - 32 bit fixed-point index, ///////////////////////////////////////////////// wv32.InitWT(frequency, WT_SAW); Generate(duration, &wv32, &eg); //GenerateVib(duration, &wv32, &eg, lfoAmp); //GeneratePhaseVib(duration, &wv32, &eg, lfoAmp); ///////////////////////////////////////////////// // 6 - 64 bit fixed-point index, ///////////////////////////////////////////////// //wv64.InitWT(frequency, WT_SAW); //Generate(duration, &wv64, &eg); //GenerateVib(duration, &wv64, &eg, lfoAmp); //GeneratePhaseVib(duration, &wv64, &eg, lfoAmp); Silence(0.25); ///////////////////////////////////////////////// // 7 - square wave (summation) ///////////////////////////////////////////////// wv.InitWT(frequency, WT_SQR); Generate(duration, &wv, &eg); //GenerateVib(duration, &wv, &eg, lfoAmp); //GeneratePhaseVib(duration, &wv, &eg, lfoAmp); ///////////////////////////////////////////////// // 8 - triangle wave (summation) ///////////////////////////////////////////////// wv.InitWT(frequency, WT_TRI); Generate(duration, &wv, &eg); Silence(0.25); ///////////////////////////////////////////////// // 9 - FM ///////////////////////////////////////////////// wvfm.InitFM(frequency/2, 2.0, 1.0, WT_SIN); Generate(duration, &wvfm, &eg); wvfm.InitFM(frequency, 2.0, 1.0, WT_SIN); Generate(duration, &wvfm, &eg); //GenerateVib(duration, &wvfm, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvfm, &eg, lfoAmp); Silence(0.25); ///////////////////////////////////////////////// // 10 - Amplitude Modulation ///////////////////////////////////////////////// wvam.InitAM(frequency, frequency*2.5, 1.0, WT_SIN); Generate(duration, &wvam, &eg); ///////////////////////////////////////////////// // 11 - Ring Modulation ///////////////////////////////////////////////// wvrm.InitAM(frequency, frequency*2.5, 1.0, WT_SIN); Generate(duration, &wvrm, &eg); Silence(0.25); ///////////////////////////////////////////////// // 12 - Dynamic summing: sawtooth ///////////////////////////////////////////////// GenWaveSum wvs; AmpValue mult[8]; AmpValue amps[8]; for (int pnum = 0; pnum < 8; pnum++) { AmpValue x = (AmpValue)pnum + 1; mult[pnum] = x; amps[pnum] = 1.0/x; if (pnum & 1) amps[pnum] = -amps[pnum]; } wvs.InitParts(8, mult, amps, 1); wvs.InitWT(frequency, WT_SIN); Generate(duration, &wvs, &eg); //GenerateVib(duration, &wvs, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvs, &eg, lfoAmp); ///////////////////////////////////////////////// // 13 - Dynamic summing: doubling at the fifth ///////////////////////////////////////////////// mult[0] = 1.0f; mult[1] = 1.5f; amps[0] = 0.5f; amps[1] = 0.5f; wvs.InitParts(2, mult, amps, 0); wvs.InitWT(frequency, WT_SAW); Generate(duration, &wvs, &eg); //GenerateVib(duration, &wvs, &eg, lfoAmp); ///////////////////////////////////////////////// // 14 - Dynamic summing: chorus effect, two notes at slightly different frequency ///////////////////////////////////////////////// mult[0] = 1.0; mult[1] = 1.001; amps[0] = 0.6; amps[1] = 0.4; wvs.InitParts(2, mult, amps, 0); wvs.InitWT(frequency, WT_SAW); Generate(duration, &wvs, &eg); //GenerateVib(duration, &wvs, &eg, lfoAmp); Silence(0.25); // For comparison: ///////////////////////////////////////////////// // 15 - Sine wave Direct ///////////////////////////////////////////////// GenWave wvsin; wvsin.Init(1, &frequency); Generate(duration, &wvsin, &eg); //GenerateVib(duration, &wvsin, &eg, lfoAmp); ///////////////////////////////////////////////// // 16 - Sawtooth Direct ///////////////////////////////////////////////// GenWaveSaw wvsaw; wvsaw.Init(1, &frequency); Generate(duration, &wvsaw, &eg); //GenerateVib(duration, &wvsaw, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvsaw, &eg, lfoAmp); ///////////////////////////////////////////////// // 17 - Triangle Direct ///////////////////////////////////////////////// GenWaveTri wvtri; wvtri.Init(1, &frequency); Generate(duration, &wvtri, &eg); //GenerateVib(duration, &wvtri, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvtri, &eg, lfoAmp); ///////////////////////////////////////////////// // 18 - Square Direct ///////////////////////////////////////////////// GenWaveSqr wvsqr; wvsqr.InitSqr(frequency, 50.0); Generate(duration, &wvsqr, &eg); //GenerateVib(duration, &wvsqr, &eg, lfoAmp); //GeneratePhaseVib(duration, &wvsqr, &eg, lfoAmp); ///////////////////////////////////////////////// // 19 - Square Direct Integer ///////////////////////////////////////////////// GenWaveSqr32 wvsqr32; wvsqr32.InitSqr(frequency, 50.0); Generate(duration, &wvsqr32, &eg); Silence(0.25); ///////////////////////////////////////////////// // 20 - White Noise ///////////////////////////////////////////////// GenNoise wvn; Generate(duration, &wvn, &eg); ///////////////////////////////////////////////// // 21 - 'H' White Noise (sampled) ///////////////////////////////////////////////// GenNoiseH wvnh; float h; for (h = 2000.0; h < 10000.0; h += 2000.0) { wvnh.Init(1, &h); Generate(duration, &wvnh, &eg); } ///////////////////////////////////////////////// // 21 - 'Interploated' White Noise ///////////////////////////////////////////////// GenNoiseI wvni; for (h = 2000.0; h < 10000.0; h += 2000.0) { wvni.Init(1, &h); Generate(duration, &wvni, &eg); } Silence(0.25); ///////////////////////////////////////////////// // 22 - "Pink-ish" Noise (FIR filter) ///////////////////////////////////////////////// GenNoisePink1 wvp1; Generate(duration, &wvp1, &eg); ///////////////////////////////////////////////// // 23 - "Pink-ish" Noise (IIR filter) ///////////////////////////////////////////////// GenNoisePink2 wvp2; Generate(duration, &wvp2, &eg); Silence(0.25); ///////////////////////////////////////////////// // 23 - Pitched Noise (ring modulation of sine wave and noise) ///////////////////////////////////////////////// GenWaveNZ wvnzp; wvnzp.InitNZ(500.0, 400.0, WT_SIN); Generate(duration, &wvnzp, &eg); wvnzp.InitNZ(800.0, 400.0, WT_SIN); Generate(duration, &wvnzp, &eg); Silence(0.25); ///////////////////////////////////////////////// // 24 - BUZZ generator ///////////////////////////////////////////////// GenWaveBuzz buzz; buzz.InitBuzz(frequency, 20); Generate(duration, &buzz, &eg); buzz.InitBuzz(frequency, 100); Generate(duration, &buzz, &eg); // buzz.InitBuzz(frequency, 100); // GenerateVib(duration, &buzz, &eg, lfoAmp); // GeneratePhaseVib(duration, &buzz, &eg, lfoAmp); Silence(0.25); GenWaveBuzz2 buzz2; buzz2.InitBuzz(frequency, 20); Generate(duration, &buzz2, &eg); buzz2.InitBuzz(frequency, 100); Generate(duration, &buzz2, &eg); Silence(0.25); GenWaveBuzzA buzza; // buzza.SetOscillatorA(new GenWaveI); // buzza.SetOscillatorB(new GenWaveI); buzza.InitBuzz(frequency, 20); Generate(duration, &buzza, &eg); buzza.InitBuzz(frequency, 100); Generate(duration, &buzza, &eg); Silence(0.25); GenWaveDS ds; ds.InitDS(frequency, 0.5); Generate(duration, &ds, &eg); ds.InitDS(frequency, 0.95); Generate(duration, &ds, &eg); Silence(0.25); GenWaveDSB gbz; gbz.InitDSB(frequency, 1, 100, 0.5); Generate(duration, &gbz, &eg); gbz.InitDSB(frequency, 1, 100, 0.95); Generate(duration, &gbz, &eg); // Odd harmonics, like square wave gbz.InitDSB(frequency, 2, 100, 0.5); Generate(duration, &gbz, &eg); gbz.InitDSB(frequency, 2, 100, 0.95); Generate(duration, &gbz, &eg); ///////////////////////////////////////////////// if (wvf.CloseWaveFile()) perror("Close"); return 0; }
//----------------------------------------------------------------------------- // WAVE file test void TestWaveFile() { WaveFile file; file.Load("/home/abelov/Stuff/View/Sound/Clean Guitar/Clean Guitar_1-12.wav"); }
void Silence(FrqValue duration) { long totalSamples = (long) ((duration * synthParams.sampleRate) + 0.5); for (long n = 0; n < totalSamples; n++) wvf.Output1(0); }