public static byte[] PathToByte2(string path){
			//byte[] pathData=null;
			Log.Debug ("ImageToByte", "Inicia path to byte");
			Log.Debug ("ImageToByte", "Se crea el nuevo file");
			var imgFile = new Java.IO.File(path);
			Log.Debug ("ImageToByte", "Se crea el nuevo stream");
			var stream = new Java.IO.FileInputStream(imgFile);
			Log.Debug ("ImageToByte", "Se Crea el archivo Byte");
			var bytes = new byte[imgFile.Length()];
			Log.Debug ("ImageToByte", "Se hace el Stream Read");
			stream.Read(bytes);
			stream.Close ();
			stream.Dispose ();
			return bytes;

		}
Beispiel #2
0
        private void StartAsync()
        {
            try
            {
                if (_player == null)
                {
                    _player = new MediaPlayer();
                }
                else
                {
                    _player.Reset();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                Java.IO.File            file = new Java.IO.File(Compliance_Activity.filePath);
                Java.IO.FileInputStream fis  = new Java.IO.FileInputStream(file);
                //_player.SetDataSourceAsync(fis.);

                _player.SetDataSource(filePath);
                _player.Prepare();
            }

            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
            }
        }
        public async Task StartPlayerAsync()
        {
            try
            {
                if (player == null)
                {
                    player = new MediaPlayer();
                }
                else
                {
                    player.Reset();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                Java.IO.File            file = new Java.IO.File(filePath);
                Java.IO.FileInputStream fis  = new Java.IO.FileInputStream(file);
                await player.SetDataSourceAsync(fis.FD);

                player.Prepare();
                player.Start();
            }
            catch (Exception ex)
            {
                AddTxt(ex.ToString().Substring(0, 400));
            }
        }
        private async Task <string> SaveFileToFolder(Android.Net.Uri uri, string fileName)
        {
            Android.Net.Uri docUri = Android.Provider.DocumentsContract.BuildDocumentUriUsingTree(uri,
                                                                                                  Android.Provider.DocumentsContract.GetTreeDocumentId(uri));

            string fileFolder = SAFFileUtil.GetPath(this, docUri);

            Java.IO.File destFolder = new Java.IO.File(fileFolder);
            Java.IO.File file       = new Java.IO.File(destFolder, fileName);
            Java.IO.File tempFile   = new Java.IO.File(TempFilePath);
            destFolder.Mkdirs();
            if (!file.Exists())
            {
                file.CreateNewFile();
            }

            Java.IO.FileInputStream  fileInput  = new Java.IO.FileInputStream(tempFile);
            Java.IO.FileOutputStream fileOutput = new Java.IO.FileOutputStream(file, false);

            while (true)
            {
                byte[] data = new byte[1024];
                int    read = await fileInput.ReadAsync(data, 0, data.Length);

                if (read <= 0)
                {
                    break;
                }
                await fileOutput.WriteAsync(data, 0, read);
            }
            fileInput.Close();
            fileOutput.Close();

            return(file.AbsolutePath);
        }
        private async Task<MediaMetadataRetriever> GetMetadataRetriever(IMediaFile currentFile)
        {
            MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();

            switch (currentFile.Type)
            {
                case MediaFileType.AudioUrl:
                    await metaRetriever.SetDataSourceAsync(currentFile.Url, _requestHeaders);
                    break;
                case MediaFileType.VideoUrl:
                    break;
                case MediaFileType.AudioFile:
                    Java.IO.File file = new Java.IO.File(currentFile.Url);
                    Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file);
                    await metaRetriever.SetDataSourceAsync(inputStream.FD);
                    break;
                case MediaFileType.VideoFile:
                    break;
                case MediaFileType.Other:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }


            return metaRetriever;
        }
Beispiel #6
0
        private static string filePath = "";//"/data/data/Example_WorkingWithAudio.Example_WorkingWithAudio/files/testAudio.mp4";

        public async Task StartPlayerAsync()
        {
            try
            {
                Java.IO.File sdDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
                filePath = sdDir + "/" + "testAudio.mp3";
                if (player == null)
                {
                    player = new MediaPlayer();
                }
                else
                {
                    player.Reset();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                Java.IO.File            file = new Java.IO.File(filePath);
                Java.IO.FileInputStream fis  = new Java.IO.FileInputStream(file);
                await player.SetDataSourceAsync(fis.FD);

                //player.SetDataSource(filePath);
                player.Prepare();
                player.Start();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
            }
        }
Beispiel #7
0
        partial void InitializeImpl()
        {
            using (var inputFile = new Java.IO.File(mediaDataUrl))
            {
                if (!inputFile.CanRead())
                {
                    throw new Exception(string.Format("Unable to read: {0} ", inputFile.AbsolutePath));
                }

                using (var inputFileStream = new Java.IO.FileInputStream(inputFile.AbsolutePath))
                {
                    var audioMediaExtractor = new MediaExtractor();
                    audioMediaExtractor.SetDataSource(inputFileStream.FD, startPosition, length);
                    var trackIndexAudio = StreamedBufferSoundSource.FindAudioTrack(audioMediaExtractor);
                    if (trackIndexAudio < 0)
                    {
                        return;
                    }

                    audioMediaExtractor.SelectTrack(trackIndexAudio);
                    var audioFormat = audioMediaExtractor.GetTrackFormat(trackIndexAudio);

                    //Get the audio settings
                    //should we override the settings (channels, sampleRate, ...) from DynamicSoundSource?
                    Channels      = audioFormat.GetInteger(MediaFormat.KeyChannelCount);
                    SampleRate    = audioFormat.GetInteger(MediaFormat.KeySampleRate);
                    MediaDuration = TimeSpanExtensions.FromMicroSeconds(audioFormat.GetLong(MediaFormat.KeyDuration));
                }
            }
        }
Beispiel #8
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                byte[] bytes;

                try
                {
                    using (var stream = new Java.IO.FileInputStream(arquivoImagem)) {
                        bytes = new byte[arquivoImagem.Length()];
                        stream.Read(bytes);
                    }
                } catch
                {
                    Bitmap bitmap = (Bitmap)data.Extras.Get("data");
                    bytes = new byte[bitmap.Width * bitmap.Height * 4];
                    using (var stream = new MemoryStream()) {
                        bitmap.Compress(Bitmap.CompressFormat.Png, 80, stream);
                        stream.Flush();
                    }
                }

                MessagingCenter.Send <byte[]>(bytes, "FotoTirada");
            }
        }
Beispiel #9
0
        public void InitMedia(string dbName)
        {
            LogManager.WriteSystemLog("initMedia" + dbName);
            player     = new MediaPlayer();
            playerloop = new MediaPlayer();
            var FolderName = dbName.Split('-')[2].Substring(0, dbName.Split('-')[2].Length - 3);

            LoopMediaPath = Android.OS.Environment.ExternalStorageDirectory + "/" + "loop.mp3";
            BreakePath    = Android.OS.Environment.ExternalStorageDirectory + "/" + FolderName + "/" + "brake.wav";
            DongPath      = Android.OS.Environment.ExternalStorageDirectory + "/" + FolderName + "/" + "dong.wav";


            Java.IO.File file = new Java.IO.File(BreakePath);
            if (File.Exists(BreakePath))
            {
                fis = new Java.IO.FileInputStream(file);
            }
            file = new Java.IO.File(LoopMediaPath);
            if (File.Exists(LoopMediaPath))
            {
                fisloop = new Java.IO.FileInputStream(file);
            }
            if (File.Exists(DongPath))
            {
                file     = new Java.IO.File(DongPath);
                dongfile = new Java.IO.FileInputStream(file);
            }
        }
Beispiel #10
0
        private async void PlayAudio(string fileName)
        {
            Console.WriteLine("Play: " + fileName);

            if (player == null)
            {
                IntializePlayer();
            }
            player.SetVolume(1, 1);
            if (player.IsPlaying)
            {
                return;
            }

            try
            {
                Java.IO.FileInputStream fis = new Java.IO.FileInputStream(audioStoragePath + fileName);
                await player.SetDataSourceAsync(fis.FD);

                player.PrepareAsync();
                AquireWifiLock();
                StartForeground();
            }
            catch (Exception ex) {
                //unable to start playback log error
                Console.WriteLine("Unable to start playback: " + ex);
            }
        }
Beispiel #11
0
        private async Task <MediaMetadataRetriever> GetMetadataRetriever(IMediaFile currentFile)
        {
            MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();

            switch (currentFile.Type)
            {
            case MediaFileType.AudioUrl:
                await metaRetriever.SetDataSourceAsync(currentFile.Url, _requestHeaders);

                break;

            case MediaFileType.VideoUrl:
                break;

            case MediaFileType.AudioFile:
                Java.IO.File            file        = new Java.IO.File(currentFile.Url);
                Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file);
                await metaRetriever.SetDataSourceAsync(inputStream.FD);

                break;

            case MediaFileType.VideoFile:
                break;

            case MediaFileType.Other:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }


            return(metaRetriever);
        }
Beispiel #12
0
 public void SpeakBreakeVoice()
 {
     try
     {
         if (fis == null)
         {
             Java.IO.File file = new Java.IO.File(BreakePath);
             if (File.Exists(BreakePath))
             {
                 fis = new Java.IO.FileInputStream(file);
             }
         }
         if (fis != null)
         {
             player.Reset();
             player.SetDataSource(fis.FD);
             player.Prepare();
             player.Start();
         }
     }
     catch (Exception ex)
     {
         LogManager.WriteSystemLog("SpeakBreake:" + ex.Message + ":" + ex.Source + ":" + ex);
     }
 }
Beispiel #13
0
        public async Task StartPlayerAsync()
        {
            try
            {
                if (player == null)
                {
                    player = new MediaPlayer();
                }
                else
                {
                    player.Reset();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                Java.IO.File            file = new Java.IO.File(filePath);
                Java.IO.FileInputStream fis  = new Java.IO.FileInputStream(file);
                await player.SetDataSourceAsync(fis.FD);

                //player.SetDataSource(filePath);
                player.Prepare();
                player.Start();
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.StackTrace);
            }
        }
 public StreamConverter(Java.IO.FileInputStream fileInputStream, Action <int> progress)
 {
     _fileInputStream = fileInputStream;
     CanRead          = true;
     CanSeek          = false;
     CanWrite         = false;
     Length           = fileInputStream.Available();
     _progressAction  = progress;
 }
        private void ExtractVideoPickedFromGallery(Intent data)
        {
            try {
                Android.Net.Uri selectedUri = data.Data;

                string mimeType = "video";

                PickedMediaFromGallery result = new PickedMediaFromGallery();

                if (mimeType.StartsWith("video"))
                {
                    string filePath = MediaUtils.GetFileFullPathAlternativeVideo(data.Data, this);

                    Java.IO.File videoFile = new Java.IO.File(filePath);

                    Java.IO.FileInputStream videoFileInputStream = new Java.IO.FileInputStream(videoFile);
                    byte[] videoFileBytes = new byte[videoFile.Length()];
                    videoFileInputStream.Read(videoFileBytes);
                    videoFileInputStream.Close();
                    videoFileInputStream.Dispose();

                    System.IO.Stream thumbnailStream = DependencyService.Get <IPickMediaDependencyService>().GetThumbnail(filePath);
                    byte[]           thumbnailBytes;

                    thumbnailStream.Position = 0;

                    using (System.IO.BinaryReader reader = new System.IO.BinaryReader(thumbnailStream)) {
                        thumbnailBytes = reader.ReadBytes((int)thumbnailStream.Length);
                    }

                    result = new PickedMediaFromGallery()
                    {
                        Completion          = true,
                        DataBase64          = Android.Util.Base64.EncodeToString(videoFileBytes, Android.Util.Base64Flags.Default),
                        DataThumbnailBase64 = Convert.ToBase64String(thumbnailBytes),
                        FilePath            = filePath,
                        MimeType            = ProfileMediaService.VIDEO_MEDIA_TYPE
                    };
                }
                else
                {
                    Debugger.Break();
                    throw new InvalidOperationException();
                }

                PickVideoTaskCompletion.SetResult(result);
            }
            catch (Exception exc) {
                Debugger.Break();

                PickVideoTaskCompletion.SetResult(new PickedMediaFromGallery()
                {
                    Exception = exc, ErrorMessage = _EXTRACTION_MEDIA_MEDIA_PICK_ERROR
                });
            }
        }
 private async Task SetMediaPlayerDataSourceUsingFileDescriptor()
 {
     Java.IO.File file = new Java.IO.File(CurrentFile.Url);
     Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file);
     _mediaPlayer?.Reset();
     var dataSourceAsync = _mediaPlayer?.SetDataSourceAsync(inputStream.FD);
     if (dataSourceAsync != null)
         await dataSourceAsync;
     inputStream.Close();
 }
        public void Initialize(IServiceRegistry services, string url, long startPosition, long length)
        {
            if (isInitialized)
            {
                return;
            }

            try
            {
                inputFile = new Java.IO.File(url);
                if (!inputFile.CanRead())
                {
                    throw new Exception(string.Format("Unable to read: {0} ", inputFile.AbsolutePath));
                }

                inputFileDescriptor = new Java.IO.FileInputStream(inputFile);

                // ===================================================================================================
                // Initialize the audio media extractor
                mediaExtractor = new MediaExtractor();
                mediaExtractor.SetDataSource(inputFileDescriptor.FD, startPosition, length);

                var videoTrackIndex = FindTrack(mediaExtractor, MediaType.Video);
                var audioTrackIndex = FindTrack(mediaExtractor, MediaType.Audio);
                HasAudioTrack = audioTrackIndex >= 0;

                mediaTrackIndex = MediaType == MediaType.Audio ? audioTrackIndex : videoTrackIndex;
                if (mediaTrackIndex < 0)
                {
                    throw new Exception(string.Format($"No {MediaType} track found in: {inputFile.AbsolutePath}"));
                }

                mediaExtractor.SelectTrack(mediaTrackIndex);

                var trackFormat = mediaExtractor.GetTrackFormat(mediaTrackIndex);
                MediaDuration = TimeSpanExtensions.FromMicroSeconds(trackFormat.GetLong(MediaFormat.KeyDuration));

                ExtractMediaMetadata(trackFormat);

                // Create a MediaCodec mediadecoder, and configure it with the MediaFormat from the mediaExtractor
                // It's very important to use the format from the mediaExtractor because it contains a copy of the CSD-0/CSD-1 codec-specific data chunks.
                var mime = trackFormat.GetString(MediaFormat.KeyMime);
                MediaDecoder = MediaCodec.CreateDecoderByType(mime);
                MediaDecoder.Configure(trackFormat, decoderOutputSurface, null, 0);

                isInitialized = true;

                StartWorker();
            }
            catch (Exception e)
            {
                Release();
                throw e;
            }
        }
Beispiel #18
0
        async void Play()
        {
            if (_paused && _player != null)
            {
                _paused = false;
                //We are simply paused so just start again
                _player.Start();
                StartForeground();
                return;
            }

            if (_player == null)
            {
                IntializePlayer();
            }

            if (_player.IsPlaying)
            {
                return;
            }

            try
            {
                if (CurrentEpisode == null ||
                    Math.Abs(CurrentEpisode.Duration - CurrentEpisode.CurrentTime) < COMPARISON_EPSILON ||
                    !AudioDownloader.HasLocalFile(CurrentEpisode.RemoteUrl, CurrentEpisode.FileSize))
                {
                    return;
                }
                var file = new Java.IO.File(AudioDownloader.GetFilePath(CurrentEpisode.RemoteUrl));
                var fis  = new Java.IO.FileInputStream(file);

                // TODO reorganize it to play selected audio.
                // await player.SetDataSourceAsync(ApplicationContext, Net.Uri.Parse(Mp3
                await _player.SetDataSourceAsync(fis.FD);

                var focusResult = _audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
                if (focusResult != AudioFocusRequest.Granted)
                {
                    Log.Debug(DEBUG_TAG, "Could not get audio focus");
                }

                _player.Prepare();
                CurrentPosition = (int)CurrentEpisode.CurrentTime;

                AquireWifiLock();
                StartForeground();
            }
            catch (Exception ex)
            {
                Log.Debug(DEBUG_TAG, "Unable to start playback: " + ex);
            }
        }
Beispiel #19
0
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     base.OnActivityResult(requestCode, resultCode, data);
     if (resultCode == Result.Ok)
     {
         byte[] bytes;
         using (var stream = new Java.IO.FileInputStream(arquivoImagem))
         {
             bytes = new byte[arquivoImagem.Length()];
             stream.Read(bytes);
         }
         MessagingCenter.Send <byte[]>(bytes, "TirarFoto");
     }
 }
        public InputStreamInvoker(Java.IO.InputStream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            BaseInputStream = stream;

            Java.IO.FileInputStream fileStream = stream as Java.IO.FileInputStream;
            if (fileStream != null)
            {
                BaseFileChannel = fileStream.Channel;
            }
        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (resultCode == Result.Ok)
            {
                byte[] bytes;

                using (var stream = new Java.IO.FileInputStream(FileImagePath))
                {
                    bytes = new byte[FileImagePath.Length()];
                    stream.Read(bytes);
                }
                MessagingCenter.Send <byte[]>(bytes, "ProfilePicture");
            }
        }
Beispiel #22
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                byte[] bytes;
                using (var stream = new Java.IO.FileInputStream(foto))
                {
                    bytes = new byte[foto.Length()];
                    stream.Read(bytes);
                }
                MessagingCenter.Send(bytes, "FotoTirada");
            }
        }
        partial void ReleaseMediaInternal()
        {
            audioMediaDecoder?.Stop();
            audioMediaDecoder?.Release();
            audioMediaDecoder = null;

            audioMediaExtractor?.Release();
            audioMediaExtractor = null;

            InputFileStream?.Dispose();
            InputFileStream = null;

            InputFile?.Dispose();
            InputFile = null;
        }
Beispiel #24
0
        public void InputStreamTest()
        {
            string path = Path.GetTempFileName();
            string text = "Your're so good looking!";

            File.WriteAllText(path, text);
            Java.IO.FileInputStream      fileStream = new Java.IO.FileInputStream(path);
            Java.IO.ByteArrayInputStream byteStream = new Java.IO.ByteArrayInputStream(Encoding.ASCII.GetBytes(text));

            using (var stream = new InputStreamInvoker(fileStream)) {
                byte[] bytes = new byte[text.Length];
                Assert.IsTrue(stream.CanRead);
                Assert.IsTrue(stream.CanSeek);
                Assert.IsFalse(stream.CanTimeout);
                Assert.IsFalse(stream.CanWrite);
                Assert.AreEqual(stream.Length, 24);
                Assert.AreEqual(stream.Seek(8, SeekOrigin.Begin), 8);
                Assert.AreEqual(stream.Position, 8);
                Assert.AreEqual(stream.Read(bytes, 0, 7), 7);
                Assert.AreEqual("so good", Encoding.ASCII.GetString(bytes, 0, 7));
                Assert.AreEqual(stream.Seek(1, SeekOrigin.Current), 16);
                Assert.AreEqual(stream.Read(bytes, 0, 7), 7);
                Assert.AreEqual("looking", Encoding.ASCII.GetString(bytes, 0, 7));
                Assert.AreEqual(stream.Seek(-text.Length, SeekOrigin.End), 0);
                Assert.AreEqual(stream.Read(bytes, 0, 7), 7);
                Assert.AreEqual("Your're", Encoding.ASCII.GetString(bytes, 0, 7));
                stream.Position = text.Length - 1;
                Assert.AreEqual(stream.Read(bytes, 0, 1), 1);
                Assert.AreEqual("!", Encoding.ASCII.GetString(bytes, 0, 1));
            }

            using (var stream = new InputStreamInvoker(byteStream)) {
                byte[] bytes = new byte[text.Length];
                Assert.IsTrue(stream.CanRead);
                Assert.IsFalse(stream.CanSeek);
                Assert.IsFalse(stream.CanTimeout);
                Assert.IsFalse(stream.CanWrite);
                Assert.Throws <NotSupportedException> (() => { var _ = stream.Length; });
                Assert.Throws <NotSupportedException> (() => { var _ = stream.Position; });
                Assert.Throws <NotSupportedException> (() => { stream.Position = 1; });
                Assert.Throws <NotSupportedException> (() => { stream.Seek(1, SeekOrigin.Begin); });
                Assert.AreEqual(stream.Read(bytes, 0, text.Length), text.Length);
                Assert.AreEqual(text, Encoding.ASCII.GetString(bytes, 0, text.Length));
            }

            File.Delete(path);
        }
        partial void InitializeMediaExtractor(string mediaDataUrl, long startPosition, long length)
        {
            if (mediaDataUrl == null)
            {
                throw new ArgumentNullException(nameof(mediaDataUrl));
            }

            ReleaseMediaInternal();

            InputFile = new Java.IO.File(mediaDataUrl);
            if (!InputFile.CanRead())
            {
                throw new Exception(string.Format("Unable to read: {0} ", InputFile.AbsolutePath));
            }

            InputFileStream = new Java.IO.FileInputStream(InputFile.AbsolutePath);

            audioMediaExtractor = new MediaExtractor();
            audioMediaExtractor.SetDataSource(InputFileStream.FD, startPosition, length);
            trackIndexAudio = FindAudioTrack(audioMediaExtractor);
            if (trackIndexAudio < 0)
            {
                ReleaseMediaInternal();
                Logger.Error($"The input file '{mediaDataUrl}' does not contain any audio track.");
                return;
            }

            audioMediaExtractor.SelectTrack(trackIndexAudio);
            var audioFormat = audioMediaExtractor.GetTrackFormat(trackIndexAudio);

            var mime = audioFormat.GetString(MediaFormat.KeyMime);

            audioMediaDecoder = MediaCodec.CreateDecoderByType(mime);
            audioMediaDecoder.Configure(audioFormat, null, null, 0);

            //Get the audio settings
            //should we override the settings (channels, sampleRate, ...) from DynamicSoundSource?
            Channels      = audioFormat.GetInteger(MediaFormat.KeyChannelCount);
            SampleRate    = audioFormat.GetInteger(MediaFormat.KeySampleRate);
            MediaDuration = TimeSpanExtensions.FromMicroSeconds(audioFormat.GetLong(MediaFormat.KeyDuration));

            audioMediaDecoder.Start();

            extractionOutputDone = false;
            extractionInputDone  = false;
        }
        public ChannelStream(ParcelFileDescriptor parcelFileDescriptor, string mode)
        {
            _mode = mode;
            ParcelFileDescriptor = parcelFileDescriptor;

            if (mode.Contains("w"))
            {
                var outStream = new Java.IO.FileOutputStream(parcelFileDescriptor.FileDescriptor);
                Channel = outStream.Channel;
                _stream = outStream;
            }
            else
            {
                var inStream = new Java.IO.FileInputStream(parcelFileDescriptor.FileDescriptor);
                Channel = inStream.Channel;
                _stream = inStream;
            }
        }
Beispiel #27
0
 public SpeechManager(Context context, bool IsPlayActionVoice = true)
 {
     this.mContext      = context;                               //获取上下文
     this.mTextToSpeech = new TextToSpeech(this.mContext, this); //实例化TTS
     mTextToSpeech.SetPitch(0.5f);                               // 
     ///InitSpeechPlay();
     ///InitSpeechPlay();
     ///InitSpeechPlay();
     ///TODO:没有刹车音频文件是会报错的,所以这个是需要注意的
     InitSpeechPlayTimer();
     BreakePath = Android.OS.Environment.ExternalStorageDirectory + "/" + "brake.wav";
     player     = new MediaPlayer();
     Java.IO.File file = new Java.IO.File(BreakePath);
     if (file.Exists())
     {
         fis = new Java.IO.FileInputStream(file);
     }
 }
        //Tratando o resultado da activity, caira nesse trecho mesmo se o usuario aceitar ou nao
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)   //somente se o usuario nao cancelar a foto

            //Como vamos passar a imagem para o projeto portable precisamos transformar em um array de bytes
            {
                byte[] bytes;
                using (var stream = new Java.IO.FileInputStream(arquivoImagem))
                {
                    bytes = new byte[arquivoImagem.Length()];
                    stream.Read(bytes);
                }

                MessagingCenter.Send <byte[]>(bytes, "FotoTirada");
            }
        }
        public virtual async Task <IMediaItem> CreateMediaItem(FileInfo file)
        {
            IMediaItem mediaItem = new MediaItem(file.FullName);

            try
            {
                var metaRetriever = new MediaMetadataRetriever();

                var javaFile    = new Java.IO.File(file.FullName);
                var inputStream = new Java.IO.FileInputStream(javaFile);
                await metaRetriever.SetDataSourceAsync(inputStream.FD);

                mediaItem = await ExtractMediaInfo(metaRetriever, mediaItem);
            }
            catch (Exception)
            {
            }
            return(mediaItem);
        }
Beispiel #30
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                //Alterado para enviar array de bytes para testes
                //MessagingCenter.Send<Java.IO.File>(arquivoImagem, "Foto");

                byte[] bytes;
                using (var stream = new Java.IO.FileInputStream(arquivoImagem))
                {
                    bytes = new byte[arquivoImagem.Length()];
                    stream.Read(bytes);
                };

                MessagingCenter.Send <byte[]>(bytes, "Foto");
            }
        }
        private void Release()
        {
            Scheduler.UnregisterExtractor(this); //to avoid receiving any more event from the scheduler

            MediaDecoder?.Stop();
            MediaDecoder?.Release();
            MediaDecoder = null;

            mediaExtractor?.Release();
            mediaExtractor = null;

            inputFile     = null;
            MediaMetadata = null;
            MediaDuration = TimeSpan.Zero;

            inputFileDescriptor?.Close();
            inputFileDescriptor = null;

            isInitialized = false;
        }
Beispiel #32
0
        private async Task <MediaMetadataRetriever> GetMetadataRetriever(IMediaFile currentFile)
        {
            var metaRetriever = new MediaMetadataRetriever();

            if (currentFile.Type == MediaFileType.Audio)
            {
                if (currentFile.Availability == ResourceAvailability.Remote)
                {
                    await metaRetriever.SetDataSourceAsync(currentFile.Url, _requestHeaders);
                }
                else
                {
                    var file        = new Java.IO.File(currentFile.Url);
                    var inputStream = new Java.IO.FileInputStream(file);
                    await metaRetriever.SetDataSourceAsync(inputStream.FD);
                }
            }

            return(metaRetriever);
        }
        public void strtPlayer()
        {
            try {
                if (player == null) {
                    player = new MediaPlayer ();
                } else {
                    player.Reset ();
                }

                // This method works better than setting the file path in SetDataSource. Don't know why.
                Java.IO.File file = new Java.IO.File (filePath);
                Java.IO.FileInputStream fis = new Java.IO.FileInputStream (file);
                player.SetDataSource (fis.FD);

                //player.SetDataSource(filePath);
                player.Prepare ();
                player.Start ();
            } catch (Exception ex) {
                Console.Out.WriteLine (ex.StackTrace);
            }
        }
Beispiel #34
0
        async void Play ()
        {
            if (_paused && _player != null)
            {
                _paused = false;
                //We are simply paused so just start again
                _player.Start ();
                StartForeground ();
                return;
            }

            if (_player == null)
            {
                IntializePlayer ();
            }

            if (_player.IsPlaying)
            {
                return;
            }

            try
            {
                if (CurrentEpisode == null ||
                    Math.Abs (CurrentEpisode.Duration - CurrentEpisode.CurrentTime) < COMPARISON_EPSILON ||
                    !AudioDownloader.HasLocalFile (CurrentEpisode.RemoteUrl, CurrentEpisode.FileSize))
                {
                    return;
                }
                var file = new Java.IO.File (AudioDownloader.GetFilePath(CurrentEpisode.RemoteUrl));
                var fis = new Java.IO.FileInputStream (file);

                // TODO reorganize it to play selected audio.
                // await player.SetDataSourceAsync(ApplicationContext, Net.Uri.Parse(Mp3
                await _player.SetDataSourceAsync (fis.FD);

                var focusResult = _audioManager.RequestAudioFocus (this, Stream.Music, AudioFocus.Gain);
                if (focusResult != AudioFocusRequest.Granted)
                {
                    Log.Debug (DEBUG_TAG, "Could not get audio focus");
                }

                _player.Prepare();
                CurrentPosition = (int) CurrentEpisode.CurrentTime;

                AquireWifiLock ();
                StartForeground ();
            }
            catch (Exception ex)
            {
                Log.Debug (DEBUG_TAG, "Unable to start playback: " + ex);
            }
        }
Beispiel #35
0
		private void playMp3(byte[] mp3SoundByteArray) {		
						try {		
								// create temp file that will hold byte array		
								Java.IO.File tempMp3 = Java.IO.File.CreateTempFile("kurchina", "mp3", CacheDir);		
								tempMp3.DeleteOnExit();		
								Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(tempMp3);		
								fos.Write(mp3SoundByteArray);		
								fos.Close();		
						
								Java.IO.FileInputStream fis = new Java.IO.FileInputStream(tempMp3);		
								player.SetDataSource(fis.FD);		
								player.Prepare();
								player.Start();		
							} catch (Java.IO.IOException ex) {		
								String s = ex.ToString ();		
								ex.PrintStackTrace ();		
						}		
				}
 private async Task SetMediaPlayerDataSourceUsingFileDescriptor()
 {
     Java.IO.File file = new Java.IO.File(CurrentFile.Url);
     Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file);
     _mediaPlayer?.Reset();
     var dataSourceAsync = _mediaPlayer?.SetDataSourceAsync(inputStream.FD);
     if (dataSourceAsync != null)
         await dataSourceAsync;
     inputStream.Close();
 }