Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Today use c++ code to write a music player. This is to draw a graphical window based on MFC and add the corresponding Button Button as a function Button and Slider Control as a volume Control.
The effect is as follows:
Void C music player Dlg::OnBnClickedOpen() {// TODO: CFileDialog (TRUE); dlg.DoModal(); // Get the path to the selected file CString strmusicPath = dlg.getPathName (); //1. Close the last music // multimedia device interface (MCI) McISendCommand (m_DeviceID, MCI_CLOSE, 0, 0); //2. Open music file MCI_OPEN_PARMS McIopenparms; mciopenparms.lpstrElementName = strmusicPath; MCIERROR mciError; mciError = mciSendCommand(NULL, MCI_OPEN, MCI_OPEN_ELEMENT | MCI_WAIT, (DWORD)&mciopenparms); If (McIError)// if McIError is true, the opening fails {wchar_t szErrorMsg[256]; mciGetErrorString(mciError, szErrorMsg, 256); // Get the error message AfxMessageBox(szErrorMsg); // An error message returns; } m_DeviceID = mciopenparms.wDeviceID; / /}Copy the code
This is the button to select a multimedia music file, click on it and select the corresponding music from the file path.
//// play void C music player Dlg::OnBnClickedPlay() {// TODO: add control notification handler code MCI_PLAY_PARMS McIpalyparms; mcipalyparms.dwCallback = NULL; mcipalyparms.dwFrom = 0; / / start from scratch playing McISendCommand (m_DeviceID MCI_PLAY, MCI_FROM | MCI_NOTIFY, (DWORD) & McIpalyparms); }Copy the code
This is when the start play button is clicked, and it responds by playing from the beginning.
Void C music player Dlg::OnBnClickedPause() {// TODO: CString STR; GetDlgItemText(IDC_PAUSE, str); If (STR == L" pause ") {McISendCommand (m_DeviceID, MCI_PAUSE, 0, 0); SetDlgItemText(IDC_PAUSE, L" continue "); } else if (STR == L" continue ") {McISendCommand (m_DeviceID, MCI_RESUME, 0, 0); SetDlgItemText(IDC_PAUSE, L" pause "); }}Copy the code
This is the response to the pause and continue play buttons.
Dlg::OnBnClickedStop() {// TODO: McISendCommand (m_DeviceID, MCI_STOP, 0, 0); mciSendCommand(m_DeviceID, MCI_CLOSE, 0, 0); }Copy the code
Finally, this is the response to the stop play button.
The complete core code, as shown above, is not as difficult as it might seem. You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.