How to get all audio files from device with MediaStore - android-studio

I am trying to get all the media files from the device Internal Storage. I used MediaStore to retrieve it but it return only one song.
Please I want it to return all song in internal Storage, but it return only one song, please help me to check where the problem is.
Here is my code main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView audioView = (ListView) findViewById(R.id.songView);
ArrayList<String> audioList = new ArrayList<>();
String[] proj = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.DISPLAY_NAME };// Can include more data for more details and check it.
Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if(audioCursor != null){
if(audioCursor.moveToFirst()){
do{
int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioList.add(audioCursor.getString(audioIndex));
}while(audioCursor.moveToNext());
}
}
audioCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1, audioList);
audioView.setAdapter(adapter);
}
}`

You can try it like this.
1st add these two permission manifests and give programmatically
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For Android 13 or higher you need only this one permission for audio
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>
And Get All Audios Like this
ArrayList<String> audioLists = new ArrayList<>();
String[] strings = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};// Can include more data for more details and check it.
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, strings, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int audioIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioLists.add(cursor.getString(audioIndex));
} while (cursor.moveToNext());
}
}
cursor.close();
for (int i = 0 ; i < audioLists.size(); i++ ){
Log.e("audioListss" ,"Audio Path ---->>> " + audioLists.get(i));
}
I get All Audios See below

Wow it now work, the problem was located in Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, proj, null, null, null);
I changed getContentResolver query to INTERNAL_CONTENT_URI coz I do not have sdcard on my device.
Thank you all for your support.

Related

Printing Duplicate Records from the Data View In Acumatica

I am trying to print all records of a data-view into a file using a for loop in my customization in Acumatica. Unfortunately I am ending up with printing the first record everytime resulting into duplication of records, Unable to track where I am going wrong....Please Assist
Here Goes my Code......
public class MayBankGIROProcess : PXGraph<MayBankGIROProcess>
{
public PXSelect<MayBankGIRO> Document; //This is my Data View
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
List<string> myList = new List<string> { };
foreach (MayBankGIRO dacRecord in this.Document.Select()) //this is the loop which is taking the data records.
{
myList.Add(dacRecord.ReordType+ "|"+ dacRecord.CustomerReferenceNumber+ "|"+ dacRecord.ClientBatchID+ "|");
// The above line is printing only the first record of the data view everytime .
}
string filename = "DAWN" + ".txt";
Download(myList, filename);
return adapter.Get();
}
public static void Download(List<string> lines, string name) //method generating file
{
var bytes = default(byte[]);
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
foreach (string line in lines)
{
sw.WriteLine(line);
}
stream.Position = 0;
bytes = stream.ToArray();
sw.Close();
};
PX.SM.FileInfo textDoc = new PX.SM.FileInfo(name, null, bytes);
if (textDoc != null)
{
throw new PXRedirectToFileException(textDoc, true);
}
else
{
PXTrace.WriteInformation("Could not generate file");
}
}
}
[Generated Text File with all duplicate Record][1]
[1]: https://i.stack.imgur.com/Kllmk.png
[Original Record from database][2]
[2]: https://i.stack.imgur.com/Rbr9k.png
This usually happens when the report is pulling from a SQL View DAC which doesn't have unique key defined. Add IsKey=True on DAC fields until the SQL view is pulling unique record and the error should go away.

NAudio.UWP Record ,Write .wav

I know that NAudio.UWP is a work in progress but the newest release (1.8) does seem to have the ability to write a .wav.
private IWavePlayer player;
private WaveStream reader;
private IWaveIn recorder;
private MemoryStream recordStream;
private IRandomAccessStream selectedStream;
private void Record()
{
if (recorder == null)
{
recorder = new WasapiCaptureRT();
recorder.RecordingStopped += RecorderOnRecordingStopped;
recorder.DataAvailable += RecorderOnDataAvailable;
}
if (reader != null)
{
reader.Dispose();
reader = null;
}
recorder.StartRecording();
}
private async void RecorderOnDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
{
Debug.WriteLine(waveInEventArgs.BytesRecorded);
if (reader == null)
{
recordStream = new MemoryStream();
reader = new RawSourceWaveStream(recordStream, recorder.WaveFormat);
}
await recordStream.WriteAsync(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
}
Where/How do you create the Storage file name, path etc? There is no destination param...This is the only code that came with the example.
**Mark if you see this Chrome is blocking the 1.8 code download.
Where/How do you create the Storage file name, path etc?
It actually depends on your requirements. For example, you could use fixed name and timestamp to named your audio file.
var file = KnownFolders.MusicLibrary.CreateFileAsync("song"+DateTime.Now.ToString("yyyy-MM-DD-hh-mm-ss")+".wav",CreationCollisionOption.GenerateUniqueName);
You could copy record stream to a new file stream. For example:
var file = await KnownFolders.MusicLibrary.CreateFileAsync("test.wav");
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
recordStream.CopyTo(stream.AsStream());
}

Access ViewController in DependencyService to present MFMailComposeViewController

How can i access the ViewController in my DependencyService to present a MFMailComposeViewController? I tried using Application.Context but this seems to be only working on Android. Any advice?
You can present a MFMailComposeViewController by doing a window.RootController.PresentViewController (mail controller, true, null);. Depending on your app architecture, the RootViewController might not be an usable ViewController in the hierarchy. In that case you get a
Warning: Attempt to present <MFMailComposeViewController: 0x16302c30> on <Xamarin_Forms_Platform_iOS_PlatformRenderer: 0x14fd1530> whose view is not in the window hierarchy!
In that case, you have to dig for the concrete ViewController, in my case it is:
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
which is a bit wicked, but works (An issue for this have been filed for future fix).
The full solution then looks like:
in your AppDelegate.cs, add this:
public UIWindow Window {
get { return window; }
}
in your PCL project, declare the interface: ISendMailService.cs
public interface ISendMailService
{
void ComposeMail (string[] recipients, string subject, string messagebody = null, Action<bool> completed = null);
}
in your iOS project, implement and register the interface: SendMailService.cs
[assembly: DependencyAttribute(typeof(SendMailService))]
public class SendMailService : ISendMailService
{
public void ComposeMail (string[] recipients, string subject, string messagebody = null, Action<bool> completed = null)
{
var controller = new MFMailComposeViewController ();
controller.SetToRecipients (recipients);
controller.SetSubject (subject);
if (!string.IsNullOrEmpty (messagebody))
controller.SetMessageBody (messagebody, false);
controller.Finished += (object sender, MFComposeResultEventArgs e) => {
if (completed != null)
completed (e.Result == MFMailComposeResult.Sent);
e.Controller.DismissViewController (true, null);
};
//Adapt this to your app structure
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
var navcontroller = rootController as UINavigationController;
if (navcontroller != null)
rootController = navcontroller.VisibleViewController;
rootController.PresentViewController (controller, true, null);
}
}
And you can now consume it from your Xamarin.Forms PCL project:
new Button {
Font = Font.SystemFontOfSize (NamedSize.Medium),
Text = "Contact us",
TextColor = Color.White,
BackgroundColor = ColorsAndStyles.LightBlue,
BorderRadius = 0,
Command = new Command (()=>{
var mailservice = DependencyService.Get<ISendMailService> ();
if (mailservice == null)
return;
mailservice.ComposeMail (new [] {"foo#example.com"}, "Test", "Hello, World");
})
}
Use: UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(controller, true, null);
I would like to add an additional answer based off of the KeyWindow not always being the main window. (this occurs when you are presenting your controller after the user has interacted with an action sheet or alert dialog)
public static UIViewController GetCurrentUIController()
{
UIViewController viewController;
var window = UIApplication.SharedApplication.KeyWindow;
if (window == null)
{
throw new InvalidOperationException("There's no current active window");
}
if (window.RootViewController.PresentedViewController == null)
{
window = UIApplication.SharedApplication.Windows
.First(i => i.RootViewController != null &&
i.RootViewController.GetType().FullName
.Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
}
viewController = window.RootViewController;
while (viewController.PresentedViewController != null)
{
viewController = viewController.PresentedViewController;
}
return viewController;
}
This will guarantee that you get the Xamarin Forms platform renderer window, then find the foremost presented ViewController and return it for use presenting whatever UI or view controller you need to present.
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(controller, true, null);
This only works in above all solutions
Just for a reference. It took me some time to figure it out how to launch it from modal window.
Here comes the solution:
var rootController = ((AppDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.PresentedViewController;
var navcontroller = rootController as UINavigationController;
if (navcontroller != null)
rootController = navcontroller.VisibleViewController;
rootController.PresentViewController (controller, true, null);

IP Camera 401 unauthorized Error

While connecting IP camera with C# app, i found the simple player in Aforge/Samples/Player. It just needed modifying the ip string so i added mine admin:admin#192.168.1.239:81/videostream.cgi?rate=11 to get MJPEG video stream. On compiling i get error as
The Remote server returned an Error (401) Unauthorized.
Andre Kirillow mentioned in MJPEGstream.cs file
Some cameras produce HTTP header, which does not conform strictly to standard, what leads to .NET exception. To avoid this exception the useUnsafeHeaderParsing configuration option of httpWebRequest should be set, what may be done using application configuration file.
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
</configuration>
well there are two ways to do this as suggested by Dinis Cruz. I added the .config file wth the above code and also did it programmaticaly but same error persists. The Player program coding is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Reflection;
using System.Net.Configuration;
using System.Net;
namespace Player
{
public partial class MainForm : Form
{
private Stopwatch stopWatch = null;
// Class constructor
public MainForm( )
{
InitializeComponent( );
}
private void MainForm_FormClosing( object sender, FormClosingEventArgs e )
{
CloseCurrentVideoSource( );
}
// "Exit" menu item clicked
private void exitToolStripMenuItem_Click( object sender, EventArgs e )
{
this.Close( );
}
// Open local video capture device
private void localVideoCaptureDeviceToolStripMenuItem_Click( object sender, EventArgs e )
{
VideoCaptureDeviceForm form = new VideoCaptureDeviceForm( );
if ( form.ShowDialog( this ) == DialogResult.OK )
{
// create video source
VideoCaptureDevice videoSource = form.VideoDevice;
// open it
OpenVideoSource( videoSource );
}
}
// Open video file using DirectShow
private void openVideofileusingDirectShowToolStripMenuItem_Click( object sender, EventArgs e )
{
if ( openFileDialog.ShowDialog( ) == DialogResult.OK )
{
// create video source
FileVideoSource fileSource = new FileVideoSource( openFileDialog.FileName );
// open it
OpenVideoSource( fileSource );
}
}
// Open JPEG URL
private void openJPEGURLToolStripMenuItem_Click( object sender, EventArgs e )
{
URLForm form = new URLForm( );
form.Description = "Enter URL of an updating JPEG from a web camera:";
form.URLs = new string[]
{
"http://195.243.185.195/axis-cgi/jpg/image.cgi?camera=1",
};
if ( form.ShowDialog( this ) == DialogResult.OK )
{
// create video source
JPEGStream jpegSource = new JPEGStream( form.URL );
// open it
OpenVideoSource( jpegSource );
}
}
// Open MJPEG URL
private void openMJPEGURLToolStripMenuItem_Click( object sender, EventArgs e )
{
URLForm form = new URLForm( );
form.Description = "Enter URL of an MJPEG video stream:";
form.URLs = new string[]
{
"http://admin#192.168.1.239:81/videostream.cgi?rate=11",
"mjpegSource by mobby"
};
if ( form.ShowDialog( this ) == DialogResult.OK )
{
// create video source
MJPEGStream mjpegSource = new MJPEGStream( form.URL );
// open it
OpenVideoSource( mjpegSource );
}
}
// Open video source
private void OpenVideoSource( IVideoSource source )
{
// set busy cursor
this.Cursor = Cursors.WaitCursor;
// stop current video source
//CloseCurrentVideoSource( );
// start new video source
videoSourcePlayer.VideoSource = source;
videoSourcePlayer.Start( );
// reset stop watch
stopWatch = null;
// start timer
timer.Start( );
this.Cursor = Cursors.Default;
}
// Close video source if it is running
private void CloseCurrentVideoSource( )
{
if ( videoSourcePlayer.VideoSource != null )
{
videoSourcePlayer.SignalToStop( );
// wait ~ 3 seconds
for ( int i = 0; i < 30; i++ )
{
if ( !videoSourcePlayer.IsRunning )
break;
System.Threading.Thread.Sleep( 100 );
}
if ( videoSourcePlayer.IsRunning )
{
videoSourcePlayer.Stop( );
}
videoSourcePlayer.VideoSource = null;
}
}
// New frame received by the player
private void videoSourcePlayer_NewFrame( object sender, ref Bitmap image )
{
DateTime now = DateTime.Now;
Graphics g = Graphics.FromImage( image );
// paint current time
SolidBrush brush = new SolidBrush( Color.Red );
g.DrawString( now.ToString( ), this.Font, brush, new PointF( 5, 5 ) );
brush.Dispose( );
g.Dispose( );
}
// On timer event - gather statistics
private void timer_Tick( object sender, EventArgs e )
{
IVideoSource videoSource = videoSourcePlayer.VideoSource;
if ( videoSource != null )
{
// get number of frames since the last timer tick
int framesReceived = videoSource.FramesReceived;
if ( stopWatch == null )
{
stopWatch = new Stopwatch( );
stopWatch.Start( );
}
else
{
stopWatch.Stop( );
float fps = 1000.0f * framesReceived / stopWatch.ElapsedMilliseconds;
fpsLabel.Text = fps.ToString( "F2" ) + " fps";
stopWatch.Reset( );
stopWatch.Start( );
}
}
}
public static bool SetAllowUnsafeHeaderParsing20()
{
//Get the assembly that contains the internal class
Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
if (aNetAssembly != null)
{
//Use the assembly in order to get the internal type for the internal class
Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
if (aSettingsType != null)
{
//Use the internal static property to get an instance of the internal settings class.
//If the static instance isn't created allready the property will create it for us.
object anInstance = aSettingsType.InvokeMember("Section",
BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
if (anInstance != null)
{
//Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
if (aUseUnsafeHeaderParsing != null)
{
aUseUnsafeHeaderParsing.SetValue(anInstance, true);
return true;
}
}
}
}
return false;
}
}
}
From google i added some open ip cameras and there video stream was captured and worked fine but my camera returns Error 401. Then I used ISPY software recently made by Sean Tearney that was built using the same Aforge library and it captures my camera's video stream:p. Now i do not know what's wrong with the simple player's coding.Kindly if some one can help me get the video stream from camera. Thankyou
most likely because the camera is protected by password. to enable you to view the stream, please provide username and password to the camera you try to access.
for jpeg stream:
jpegSource.Login = "your username";
jpegSource.Password = "your password";
for mjpeg stream:
mjpegSource.Login = "your username";
mjpegSource.Password = "your password";

Connect marker with EditPart

I have a graphical editor which extends GraphicalEditorWithFlyoutPalette.
There could be appear different markers, so it would be nice, if there is any possibility to connect the marker with the EditPart.
I think one possibility is to extend the TableViewer and the corresponding cell classes. But perhaps there is a better and more easier way.
I create my test markers like following:
IResource resource = (IResource) input.getAdapter(IResource.class);
try
{
IMarker marker = resource.createMarker(IMarker.PROBLEM);
marker.setAttribute(IMarker.TEXT, "text");
marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
marker.setAttribute(IMarker.MESSAGE, "message");
}
catch (CoreException e)
{
e.printStackTrace();
}
input is my IEditorInput.
In my first attempt, I was trying to extends the ExtendedMarkersView, which fails because it is an internal class.
Another way was to write the view and all corresponding stuff new, but it seems to be senseless.
So I found a work around based on https://stackoverflow.com/a/10501971/390177.
While creating the IMarker, I set additional attributes to link the corresponding data object. With the help of the object I can search for the AbstractGraphicalEditPart with the EditPartRegistry.
After that it is possible to create a selection on the EditPart and reveal to it.
#Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
IStructuredSelection s = (IStructuredSelection) selection;
if (s.getFirstElement() instanceof MarkerItem) {
MarkerItem marker = (MarkerItem) s.getFirstElement();
if (marker != null && marker.getMarker() != null) {
IMarker iMarker = marker.getMarker();
AbstractGraphicalEditPart editPart = null;
DataObject object ...
editPart = (AbstractGraphicalEditPart) getGraphicalViewer().getEditPartRegistry().get(object);
if (editPart != null) {
StructuredSelection eSelection = new StructuredSelection(editPart);
getGraphicalViewer().setSelection(eSelection);
// once selected if you want to get it so the
// graphicalviewer scrolls to reveal the part on the
// screen
getGraphicalViewer().reveal(editPart);
}
}
} else {
super.selectionChanged(part, selection);
}
}

Resources