The first code looks ok to me. If the code doesn't wait, the only explanation that I see is that media_playing sometimes returns 0. Can you send that project to support? We must look into it deeper.