How to use the TMediaPlayer to record sound from a microphone (Views: 714)
Problem/Question/Abstract: I'm trying to use MediaPlayer to record sound into a wave file through a microphone. Can someone show me some simple code to do the recording? Answer: The TMediaPlayer can only open a wave file that has at least one byte of data in it. I found this out when I tried to create and open a wave file that was nothing but a wave header. The TMediaPlayer wouldn't do it. The following code creates a wave file with a single byte of data at the beginning. It is a bit of a kludge to do it this way, but it works. You need to add MMSYSTEM to the uses clause of any unit that uses this function. function CreateNewWave(NewFileName: string): Boolean; var DeviceID: Word; Return: LongInt; MciOpen: TMCI_Open_Parms; MciRecord: TMCI_Record_Parms; MciPlay: TMCI_Play_Parms; MciSave: TMCI_SaveParms; MCIResult: LongInt; Flags: Word; TempFileName: array[0..255] of char; begin MediaPlayer.Close; StrPCopy(TempFileName, NewFileName); MciOpen.lpstrDeviceType := 'waveaudio'; MciOpen.lpstrElementName := ''; Flags := Mci_Open_Element or Mci_Open_Type; MCIResult := MciSendCommand(0, MCI_OPEN, Flags, LongInt(@MciOpen)); DeviceID := MciOpen.wDeviceId; MciRecord.dwTo := 1; Flags := Mci_To or Mci_Wait; MCIResult := MciSendCommand(DeviceID, Mci_Record, Flags, LongInt(@MciRecord)); mciPlay.dwFrom := 0; Flags := Mci_From or Mci_Wait; MciSendCommand(DeviceId, Mci_Play, Flags, LongInt(@MciPlay)); mciSave.lpfileName := TempFilename; Flags := MCI_Save_File or Mci_Wait; MCIResult := MciSendCommand(DeviceID, MCI_Save, Flags, LongInt(@MciSave)); Result := MciSendCommand(DeviceID, Mci_Close, 0, LongInt(nil)) = 0; end; |