This is a very good question (better than you know), and there is a lot to learn. A LOT.
I'll try to keep it short. The operating system acts as a level of abstraction between software and hardware:
Software
.
/|\
| communicates with
\|/
'
Operating System
.
/|\
| communicates with
\|/
'
Hardware
The OS communicates with the hardware through programs called drivers (widely used term), and the OS communicates with software through procedures called system calls (not-so-widely used term).
Essentially, when you make a system call, you are leaving your program and entering code of the operating system. System calls are the only way programmers are allowed to communicate with resources.
Now I would stop there, but you also said:
To me, it seems that the machine code should run at a lower level than
the operating system and therefore, I can't understand how the OS can
act as an intermediary between the compiled application and the
hardware.
This is tricky, but simple once you understand some basics.
First, all code is just machine code running on the CPU. No code is higher or lower than other code (with the exception of some commands that can only be run in a privileged kernel mode). So the question is, how can the OS possibly be in control even though it is relinquishing control of the CPU to the user?
When code is running on a CPU, there is a concept called an interrupt. This is a signal sent to the CPU that causes the currently running code to stop and get switched out with another piece of code, called an interrupt handler.
Examples of interrupts include the keyboard, the mouse, and most importantly, the clock.
The clock interrupt is raised on a regular basis causes the operating system's clock interrupt handler to run. Within this clock interrupt handler is the operating system's code that examines what code is currently running determines what code needs to run next. This can be either more operating system code or more user code.
Because the clock is always ticking, and because the operating system always gets this periodic chance to run on the CPU, it is able to orchestrate everything within the computer, even though it runs using the same set of CPU commands as any normal program.