Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C++ Builder > WAV files


Автор: JAnty 13.1.2005, 10:39
Как програмно воспроизвести простой *.wav файл? smile

Автор: azesmcar 13.1.2005, 13:38
Код

BOOL PlaySound(
 LPCSTR pszSound,  
 HMODULE hmod,    
 DWORD fdwSound    
);

Автор: mr.Anderson 14.1.2005, 21:07
А где это все писать?

Автор: Duster 15.1.2005, 13:09
Возьми компонент нужный... вроде MediaPlayer... короче в хэлпе все! все! есть по этому поводу!

Автор: InfMag 16.1.2005, 11:43
Цитата(Duster @ 15.1.2005, 13:09)
Возьми компонент нужный... вроде MediaPlayer... короче в хэлпе все! все! есть по этому поводу!

Просят же помочь произвести программно, а не компонентом. У меня тоже был трабл, производить без MP...

Автор: Nicky 16.1.2005, 23:24
Как хорошо бы было вам парни если бы умели пользоваться Help-ом в самом редакторе С smile
Код

//The following code plays a .WAV audio file named NI!.WAV twice. The first call to play doesn't return control to the application until the file is done playing. Note that if you remove the line of code that sets wait to true, the sound is only played once.

void __fastcall TForm1::Button1Click(TObject *Sender)

{
 MediaPlayer1->FileName = "ni!.wav";
 MediaPlayer1->AutoRewind = true;
 MediaPlayer1->Open(); // Open the media player
 try
 {
   MediaPlayer1->Wait = true; // don’t return until playing is done
   MediaPlayer1->Play();      // Play sound
   MediaPlayer1->Play();      // Play again after first play is completed
 }
 __finally
 {
   MediaPlayer1->Close();   // Close media player
 }
}

Автор: InfMag 17.1.2005, 00:55
Да с MP я умею пользоваться, еще с Delphi, а программно это никак не делается или придется писать огромный модуль, умеющий читать, WAV'ишки?

Автор: azesmcar 17.1.2005, 08:55
Цитата
А где это все писать?


Это функция которая будет воспроизводить WAV файл...
Пихай в событие при котором должен воспроизводиться файл...
Код

PlaySound( "C:\\play.wav", NULL, SND_FILENAME); //Если хочешь чтоб функция закончилась только тогда когда весь файл воспроизведен
PlaySound( "C:\\play.wav", NULL, SND_FILENAME|SND_ASYNC); //Если хочешь чтоб функция возвращалась сразу после вызова и файл воспроизводился асинхронно


А пихать из за воспроизведения wav файла в программу целый MediaPlayer вместо вызова одной апи функции это уже помахивает на расточителсьтво ресурсов...ну коль ресурсы не жалко пихайте smile))
Добавлено @ 09:02
не забудь lib Winmm.lib и #include <Mmsystem.h>
Добавлено @ 09:05
Код

void __fastcall TForm1::Button1Click(TObject *Sender)
{
   PlaySound( "C:\\play.wav", NULL, SND_FILENAME|SND_ASYNC);
}


еще можно так
Код

void __fastcall TForm1::Button1Click(TObject *Sender)
{
   PlaySound( "C:\\play.wav", NULL, SND_FILENAME|SND_ASYNC|SND_LOOP);
}


Будет вечно без остановки воспроизводить файл пока ты не остановишь
А останавливать надо так...
Код

void __fastcall TForm1::Button2Click(TObject *Sender)
{
   PlaySound( NULL, NULL, SND_FILENAME|SND_ASYNC);
}

Автор: InfMag 17.1.2005, 17:56
azesmcar, вот это уже другой разговор. Вот теперь и можно сказать спасибо!

Автор: Nicky 18.1.2005, 21:35
Спосибо конечно но в этой функции есть несколько недочётов с которыми может справится не каждый... smile

Автор: azesmcar 19.1.2005, 08:47
Какие недочеты??? Что то не помню никаких проблем с этой функцией...Хотя если не ошибаюсь что то там было связано с потоками, то ли если ее вызвать не в основном потоке звук не воспроизводится...точно не помню, кажется у меня что то подобное было но как решил откровенно говоря не помню...Ну если будут проблемы с использованием пишите...

Автор: Altren 26.1.2005, 23:13
А можно с этой функцией(PlaySound) воспроизводить несколько звуков паралельно? (не дожидаясь окончания предыдущего проигрывать следующий)

Автор: Nicky 27.1.2005, 01:36
Помоему в Helpe есть всё по этой функции smile

Автор: Altren 27.1.2005, 14:24
Цитата
Помоему в Helpe есть всё по этой функции
Нету

Автор: azesmcar 27.1.2005, 14:31
Цитата
Нету


Не в том help-е смотришь...MSDN надо...

Код

PlaySound( "C:\\play.wav", NULL, SND_FILENAME|SND_ASYNC); //Если хочешь чтоб функция возвращалась сразу после вызова и файл воспроизводился асинхронно


Ну и вызывай два раза, функция асинхронно работает...

Цитата

The PlaySound function plays a sound specified by the given filename, resource, or system event. (A system event may be associated with a sound in the registry or in the WIN.INI file.)

BOOL PlaySound(
  LPCSTR pszSound, 
  HMODULE hmod,   
  DWORD fdwSound   
);
Parameters
pszSound
A string that specifies the sound to play. If this parameter is NULL, any currently playing waveform sound is stopped. To stop a non-waveform sound, specify SND_PURGE in the fdwSound parameter.
Three flags in fdwSound (SND_ALIAS, SND_FILENAME, and SND_RESOURCE) determine whether the name is interpreted as an alias for a system event, a filename, or a resource identifier. If none of these flags are specified, PlaySound searches the registry or the WIN.INI file for an association with the specified sound name. If an association is found, the sound event is played. If no association is found in the registry, the name is interpreted as a filename.

hmod
Handle to the executable file that contains the resource to be loaded. This parameter must be NULL unless SND_RESOURCE is specified in fdwSound.
fdwSound
Flags for playing the sound. The following values are defined.

SND_APPLICATION The sound is played using an application-specific association.
SND_ALIAS The pszSound parameter is a system-event alias in the registry or the WIN.INI file. Do not use with either SND_FILENAME or SND_RESOURCE.
SND_ALIAS_ID The pszSound parameter is a predefined sound identifier.
SND_ASYNC The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call PlaySound with pszSound set to NULL.
SND_FILENAME The pszSound parameter is a filename.
SND_LOOP The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. You must also specify the SND_ASYNC flag to indicate an asynchronous sound event.
SND_MEMORY A sound event's file is loaded in RAM. The parameter specified by pszSound must point to an image of a sound in memory.
SND_NODEFAULT No default sound event is used. If the sound cannot be found, PlaySound returns silently without playing the default sound.
SND_NOSTOP The specified sound event will yield to another sound event that is already playing. If a sound cannot be played because the resource needed to generate that sound is busy playing another sound, the function immediately returns FALSE without playing the requested sound.
If this flag is not specified, PlaySound attempts to stop the currently playing sound so that the device can be used to play the new sound.

SND_NOWAIT If the driver is busy, return immediately without playing the sound.
SND_PURGE Sounds are to be stopped for the calling task. If pszSound is not NULL, all instances of the specified sound are stopped. If pszSound is NULL, all sounds that are playing on behalf of the calling task are stopped.
You must also specify the instance handle to stop SND_RESOURCE events.

SND_RESOURCE The pszSound parameter is a resource identifier; hmod must identify the instance that contains the resource.
SND_SYNC Synchronous playback of a sound event. PlaySound returns after the sound event completes.

Автор: Altren 27.1.2005, 17:05
Код
PlaySound( "C:\\play.wav", NULL, SND_FILENAME|SND_ASYNC); //Если хочешь чтоб функция возвращалась сразу после вызова и файл воспроизводился асинхронно
Функция возвращается сразу после вызова, но при воспр. ждет, пока кончится предыдущий звук... а потом уже проигр. новый. Беда

Автор: Altren 28.1.2005, 17:35
Чем вообще можно воспроизводить звуки без использования DirectSound и пр.? smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)