0

I made an phonegap application that plays an sound when the user clicks on the button:

 <button onclick="playAudio('test.mp3')">Play Some Audio</button>

But i want that the sound stops when the user makes an doubleclick, somehow my code dont works! Im an beginner in javascript, and think the i didnt put the variable = media in the right position. Here is my full code:

<body>
     <h1>Playing Audio</h1>

    <button onclick="playAudio('test.mp3')">Play Some Audio</button>
    <script type="text/javascript" src="cordova-2.4.0.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
        var playing = false;
        var media = null;


        function playAudio(src) {
            if (!playing) {
                if (device.platform == 'Android') {
                    src = '/android_asset/' + src;
                }

                var media = new Media(src);
                media.play();
                playing = true;
            } else {
                media.stop();
                playing = false;
            }
        }
    </script>
</body>

2 Answers 2

2

Change the following line

var media = new Media(src);

to

media = new Media(src);
Sign up to request clarification or add additional context in comments.

8 Comments

@Ian, var media = new Media(src) is creating another variable in the function scope that is separate from the variable declared in the global scope as var media = null.
@Sheikh Heera so what would you do? When i change it to media = .. nothing works even not the play audio!
You can't play or can't stop audio? Are you executing this on browser or mobile device? Do you have access to debug logs??
Before i changed it to media = newMedia(src) the play worked, with your answer nothing works! Sorry! But thanks for your help!
As long as i can not test by myself, i can only suppose what's going on... My guess is that at the moment you click to stop, media variable is not initialized yet(Don't know why the hell this would happen)... Console don't show any error??
|
2

Now i found the problem, you cannot use

 media = new Media (src) 

instead i had tu use

 my_Media = new Media (src)

There is an interreference with the word media! But what @Alexandre said was absolutley correct, and that brougt me to the final result! Thanks

1 Comment

This is why you shouldn't be using global variables - you might overwrite something. Create a scope (look up IIFE), define your variables there and attach your handlers from there. Or, if not a scope, at least a namespace (an object in the global scope into which you put your globals).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.