Cordova: Playing audio file from /public

Hey guys,
just having an issue if I try to play a file within the /public folder on my Cordova app. The sound doesn’t start playing. This is my simple code:

 var audio = new Audio('/camera_shutter.mp3');
 audio.play();

The funny thing is that an AJAX request gives me the full file:

$.get("/camera_shutter.mp3",(data) => {console.log(data)});

Also using the server url is working fine:

 var audio = new Audio('https://my-server.com/camera_shutter.mp3');
 audio.play();

Any idea why it isn’t working with localhost?

Do you get any errors in the console? Are you on a real device (which platform) or on simulator?

Yeah, if I add

audio.onerror = function(e) {
                console.log(e);
 };

audio.play();

I get an error object after 10 seconds. It has MediaError 4, which means source is not supported. But the ajax request provides the me full data of the file, including ID3 tags.

I’m using a real device (Android 6).

This one is working fine:

    var player = new window.Audio();

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    player.src = window.URL.createObjectURL(this.response);
                    player.play();
                }
            };
            xhr.open('GET', "/camera_shutter.mp3");
            xhr.responseType = 'blob';
            xhr.send();

@martijnwalraven Is there some known issue with the started web server, maybe wrong response headers?

1 Like

Did you see those suggestions about changing the path? They might help.

I guess you just need to pass the url to the plugin: http://localhost:port/path to get it working.

Which plugin do you use for that audio object? I know the media is quite famous. Here an example:
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/#mediaplay

Or do you use html5?

The most likely reason seems to be that the file is not (yet) loaded when the play method is called. But that will need some more debugging. Likely it waits when you enter the url because it understands an url would be asynchronous.

Also see: Playing a sound does not work in Meteor-Cordova app
And: https://github.com/meteor/meteor/issues/3799#issuecomment-183262780

What errors do you see in the console? The network tab likely also shows an error?