http://www.perlmonks.org?node_id=1006083

roho has asked for the wisdom of the Perl Monks concerning the following question:

I installed Win32::MediaPlayer on Windows 7 and created the following test program based on the Synopsis. The test program operates correctly and the mp3 file is played, but the 'while' loop that keeps the program from ending before the media file is finished playing uses an enormous amount of CPU (25% of my available CPU). Is there another (better) way to make the program wait until the media file has finished playing that is not so CPU intensive? My thanks to all you helpful souls in the Monastery.

#!/usr/bin/perl use strict; use warnings; use Win32::MediaPlayer; my $winmm = new Win32::MediaPlayer; $winmm->load('test1.mp3'); $winmm->play; $winmm->volume(100); while ($winmm->pos < $winmm->length) { # Loop until finished playing media file }

"Its not how hard you work, its how much you get done."

Replies are listed 'Best First'.
Re: Media Player - CPU Usage
by SuicideJunkie (Vicar) on Nov 28, 2012 at 19:01 UTC

    You're using up 100% of one of the cores checking the conditions of the while loop as fast as possible. You need to sleep between checks.

    while ('blah') { sleep 1; # in seconds select(undef,undef,undef, 0.1); # Or doze off for fractional seconds }

    Should do. Adjust the numbers depending on how much CPU you want to spend vs how quickly you want to notice that the loop condition has changed.

      Thank you! Adding sleep 1 took care of the problem. As Lotus1 pointed out below, the synopsis includes sleep 1, but it is withing an infinite while loop.

      "Its not how hard you work, its how much you get done."

Re: Media Player - CPU Usage
by Lotus1 (Vicar) on Nov 28, 2012 at 22:03 UTC

    Here is what is shown for this in the synopsis for Win32::MediaPlayer.

    while(1) { sleep 1; print 'Now Position: '.$winmm->pos(1)."\r"; # Show now tim +e. };

    To break out of the while loop you could do this:

           last unless $winmm->pos < $winmm->length;

    Update: In order to get the print statement inside the while loop to work I had to add $| = 1; at the top of the program.