A mathematical analysis of the perfectly matched layer (PML) for the time-dependent wave equation in heterogeneous and layered media is presented. We prove the stability of the PML for discontinuous media with piecewise constant coefficients, and derive energy estimates for discontinuous media with piecewise smooth coefficients. We consider a computational setup consisting of smaller structured subdomains that are discretized using high order accurate finite difference operators for approximating spatial derivatives. The subdomains are then patched together into a global domain by a weak enforcement of interface conditions using penalties. In order to ensure the stability of the discrete PML, it is necessary to transform the interface conditions to include the auxiliary variables. In the discrete setting, the transformed interface conditions are crucial in deriving discrete energy estimates analogous to the continuous energy estimates, thus proving stability and convergence of the numerical method. Finally, we present numerical experiments demonstrating the stability of the PML in a layered medium and high order accuracy of the proposed interface conditions. © 2013 Elsevier Inc.