I've developed file reader in phonegap with following path:
var defaultPath = 'file:///storage/sdcard0/';
So i'm able to list all file on sdcard and select one folder with audio files to load. So my list of audio files looks like:
i[1] = 'file:///storage/sdcard0/Download/audio/file.mp3';
i[2] = 'file:///storage/sdcard0/Download/audio/file1.mp3';
Then I try to init song using Media plugin ( installed ) with following piece of code:
var media = new Media(i[1]);
media.play();
But audio does not play or do nothing. But when I'm trying to test it using PhoneGap APP all works fine this just isn't work when I make build and try to test app from build.
I found the issue by myself.
Android does not let read files on local storage or on sdcard via path starting from root /storage/sdcard0 /storage/sdcard1. So when we would like to access local storage or sdcard we must access it via file:///mnt/sdcard/ for sdcard and file:///mnt/storage/sdcard1/ for phone storage.
Small example how to read entries from sdcard or phone storage:
var path = 'file:///mnt/storage/sdcard1/';
window.resolveLocalFileSystemURL(path, function(entry){
var reader = entry.createReader();
reader.readEntries(showEntries);
});
function showEntries(entries){
var entries = [];
for(var i =0; i < entries.length; i++){
var entry = entries[i];
var data = {
name: entry.name,
path: entry.fullPath,
};
entries[i] = data;
}
console.log(JSON.stringify(entries));
}
Hope that this will help with same issue as I had because this is not documented in phonegap.
Related
how load local html on air sdk harman, i use StageWebView on AS3, if i run on its normal view, but if i make apk and instal on android phone, its error. Application cannot showing local html. I use air SDK harman 33.1.1.554.
this my code :
var file:File = File.applicationDirectory.resolvePath("html");
var destinasi:File = File.applicationStorageDirectory;
file.copyTo(destinasi, true);
var hasil:String = "file://" + destinasi.resolvePath("index.html").nativePath;
isiMenu4.loadURL(hasil);
is there issue about security on air sdk by harman? how to skip that?
This might be an issue where you don't have Android permission to write to local storage.
Try creating the directory first and see if that throws any errors.
_file = File.applicationStorageDirectory.resolvePath("html");
trace("html.url", _file.url);
trace("html.nativePath", _file.nativePath);
if (!_file.exists) {
_file.createDirectory();
//make storage directory non backupable
_file.preventBackup = true;
}
My application records data from a patient monitor and stores it a '*.dat' file in 'Environment.SpecialFolder.Personal'.
The app also allows the user to 'play back' previously acquired recordings.
I wish to include a few sample 'dat' files within the apk. Is it possible to include such files as 'assets' in the project and have them copied to 'Environment.SpecialFolder.Personal' at the time of installation?
Copy the database into Assets folder.
And set the Build Action as AndroidAssect.
You could use the following code to copy the file from Assects folder to Android Application folder.
// Android application default folder.
var appFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var dbFile = Path.Combine(appFolder, "database.db3");
// Check if the file already exists.
if (!File.Exists(dbFile))
{
using (FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
{
// Assets is comming from the current context.
await Assets.Open(databaseName).CopyToAsync(writeStream);
}
}
Download the source file from the link below.
https://github.com/damienaicheh/CopyAssetsProject
Updated:
You could use the code below.
var assetName = "someasset.jpg";
var outputName = Path.Combine(Android.OS.Environment.DirectoryDownloads,
assetName);
using (var assetStream = context.Assets.Open(assetName))
using (var fileStream = new FileStream(outputName, FileMode.CreateNew))
{
await assetStream.CopyToAsync(fileStream);
}
If your device is higher than Android6.0, you need runtime permission.
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/android-m-runtimepermissions/
For more details, please refer to the link below.
How to save file from assets on my device? Xamarin
I am working on my first android app where you hit a button and it plays a .wav sound, it works great when I run the phonegap server app to test it but then when I package it as an .APK with phonegap build and install it on my phone, it does not play the .wav sounds.
$('.sound1').on('touchstart', function () {
var thissound = new Audio();
thissound.src = $(this).attr('key');
thissound.play();
});
The changes I made were instead of new audio(); I did new Media(); and after reading Playing Local Sound In Phonegap I found out it may have had something to do with the path needing to be an absolute local path, it works in the real packaged app now. I also discovered you need too use media.release(); because of the finite number of times you can play a sound.
$('.sound1').on('touchstart', function () {
var path = window.location.pathname;
path = path.substr( path, path.length - 10 );
var finalpath = 'file://' + path;
var key = $(this).attr('key');
var thissound = new Media( finalpath + key, function onSuccess() {
// release the media resource once finished playing
thissound.release();
} );
thissound.play();
});
It works fine on iOS.
I have looked many answers including these 2:
Play sound on Phonegap app for Android
HTML5 audio not playing in PhoneGap App (Possible to use Media?)
I have tried all of the solutions:
Changing the path to /android_asset/www/ for Android
Using .ogg files
Pre load the audio with a play() / pause().
Using the Media plugin provided by Cordova/Phonegap
Here is my current code:
if(device.platform === "Android") //DIFFERENT PATH FOR ANDROID
{
url = "/android_asset/www/sound.ogg";
}else{
url = "sound.mp3";
}
alert(url);
sound = new Media(url);
sound.play();
Anyone have an ideas?? It feels like I have been going round in circles
I had similar and this solution worked for me
Get complete path of your application using window.location.pathname, this way you dont need to worry about device type, it will give you the complete path including index.html and by using the below function simply strip off index.html from the string and append your media file.
function getPhoneGapPath() {
var path = window.location.pathname;
path = path.substr( path, path.length - 10 ); //strip off index.html
return 'file://' + path;
};
And then
url = getPhoneGapPath()+'sound.ogg'; //OR MP3
alert(url);
sound = new Media(url);
sound.play();
Hope this helps
I finally managed to get it working!!
I first initialising the audio file by finding the full Android path using #Sarim Sidd help above and then preloading the audio file:
//INITIALISE SOUND
if(device.platform === "Android") //DIFFERENT PATH FOR ANDROID
{
//navigator.notification.beep(1);
var path = window.location.pathname;
path = path.substr( path, path.length - 10 ); //strip off index.html
url = 'file://'+path+"sound.ogg";
}else{
url = "sound.mp3";
}
//sound = new Media(url);
sound = new Media(url);
sound.play();
sound.pause();
Then when to play the audio I forced the volume to full (1.0) before calling the play method. For some reason I noticed the audio kept reseting to mute each time I started the app:
//PLAY BELL SOUND THROUGH APP
sound.setVolume(1.0);
sound.play();
I have found lots of potential resolutions to this issue on StackOverflow but nothing seems to be resolving it for me. I am trying to play an mp3 file within my Cordova (3.5) app using org.apache.cordova.media#0.2.10
var sound = new Media('audio/el/hello.mp3');
sound.play()
But it just won't play and I get the following error in LogCat
MediaPlayer error (1, -2147483648)
I have tried serving the folder locally and the following works pointing at the same file
var sound = new Media('http://10.0.2.2:9999/www/audio/el/hello.mp3');
sound.play()
Which suggests that it isn't because the file has an encoding problem.
I wasn't able to use the latest version of the media plugin because the deviceready event never fires.
Update: I've just tried unzipping the files to persistent storage and playing them from there and I get the same error.
Update: Stepping through the AudioPlayer.java source it seems that the www directory is not part of the assets because the following call throws a FileNotFoundException where f == "www/el/hello.mp3"
fd = this.handler.cordova.getActivity().getAssets().openFd(f);
However If I place the files directly in the assets folder then it works.
Path of media file incorrect. You must get path correctly:
var getPathMedia = function () {
var path = window.location.pathname;
var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
// Return path at www folder
return 'file://' + phoneGapPath;
};
var media = new Media(getPathMedia() + 'media/message.mp3');
media.play();
On android, you only need to have the correct path for the www folder.
Android:
var media = new Media("/android_asset/www/audio/el/hello.mp3",
successFunction,
errorFunction
);
If your app is going to run on iOS as well, you need to add the /android_asset/www/ dynamically as iOS does not need it.
iOS:
var media = new Media("audio/el/hello.mp3",
successFunction,
errorFunction
);
I finally figured this out for myself, but I figured I'd share.
What I needed to do is not get the location, but the current url to the page I was on. From that I could construct a url to the asset I wanted to play.
var path = window.location.href;
var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
var media = new Media(phoneGapPath + 'media/message.mp3');
media.play();
hope this helps
I am using this plugin with ionic capacitor. I had to use a different filepath, when playing audiofiles that are located in assets folder. Additionally I had to call the release function after the
onSuccess-event fired. When I called it after file.play(), the playback didn't work.
var audioPath = "/android_asset/public/assets/" + "audio.mp3"
const file: MediaObject = this.media.create(audioPath)
file.onSuccess.subscribe(() => {
console.log('Action is successful')
file.release()
});
file.play();
If the audio file is not found, make sure to check that it is copied to the android project assets folder. If it is not there run "npx cap sync" and "npx cap copy".