Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save video to android device #109

Open
Juanpabloh814 opened this issue Aug 1, 2023 · 1 comment
Open

Save video to android device #109

Juanpabloh814 opened this issue Aug 1, 2023 · 1 comment
Labels
bug Something isn't working

Comments

@Juanpabloh814
Copy link

I have this code to try to save the mp4 file that is generated and said file should be saved in the specified path but it is not being saved

I really appreciate the support

using UnityEngine;
using UnityEngine.Android;
using System.Collections;
using System.IO;
using NatSuite.Recorders;
using NatSuite.Recorders.Clocks;
using NatSuite.Recorders.Inputs;

namespace NatSuite.Examples
{
public class ReplayCam : MonoBehaviour
{
[Header(@"Recording")]
public int videoWidth = 1280;
public int videoHeight = 2560;
public bool recordMicrophone;
public string videoFileName = "mi_video.mp4"; // Nombre del archivo de video

    private MP4Recorder recorder;
    private CameraInput cameraInput;
    private AudioInput audioInput;
    private AudioSource microphoneSource;
    public string videoPath;

    private void Awake()
    {
        // Request storage permission on app start
        RequestStoragePermission();
    }

    private void RequestStoragePermission()
    {
        if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
        {
            Permission.RequestUserPermission(Permission.ExternalStorageWrite);
        }
    }

    private IEnumerator Start()
    {
        // Start microphone
        microphoneSource = gameObject.AddComponent<AudioSource>();
        microphoneSource.mute = microphoneSource.loop = true;
        microphoneSource.bypassEffects = microphoneSource.bypassListenerEffects = false;
        microphoneSource.clip = Microphone.Start(null, true, 1, AudioSettings.outputSampleRate);
        yield return new WaitUntil(() => Microphone.GetPosition(null) > 0);
        microphoneSource.Play();
    }

    private void OnDestroy()
    {
        // Stop microphone
        microphoneSource.Stop();
        Microphone.End(null);
    }

    public void StartRecording()
    {
        // Start recording
        var frameRate = 30;
        var sampleRate = recordMicrophone ? AudioSettings.outputSampleRate : 0;
        var channelCount = recordMicrophone ? (int)AudioSettings.speakerMode : 0;
        var clock = new RealtimeClock();
        recorder = new MP4Recorder(videoWidth, videoHeight, frameRate, sampleRate, channelCount, audioBitRate: 96_000);
        // Create recording inputs
        cameraInput = new CameraInput(recorder, clock, Camera.main);
        audioInput = recordMicrophone ? new AudioInput(recorder, clock, microphoneSource, true) : null;
        // Unmute microphone
        microphoneSource.mute = audioInput == null;
    }

    public async void StopRecording()
    {
        // Mute microphone
        microphoneSource.mute = true;
        // Stop recording
        audioInput?.Dispose();
        cameraInput.Dispose();
        var path = await recorder.FinishWriting();

        // Ruta de la carpeta en el almacenamiento externo
        string folderName = "MyVideos"; // Nombre de la carpeta donde se guardarán los videos en el almacenamiento externo
        string externalStoragePath = Path.Combine(Application.persistentDataPath, folderName);

        // Crear la carpeta si no existe
        if (!Directory.Exists(externalStoragePath))
        {
            Directory.CreateDirectory(externalStoragePath);
        }

        // Nombre completo del archivo con la ruta en el almacenamiento externo
        videoPath = Path.Combine(externalStoragePath, videoFileName);

        // Mover el video al almacenamiento externo
        File.Move(path, videoPath);

        Debug.Log($"Saved recording to: {videoPath}");

        // Playback recording
        Handheld.PlayFullScreenMovie($"file://{videoPath}");
    }

    public void SaveVideoToGallery()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            // Obtenemos la ruta absoluta a la carpeta "Download"
            string downloadFolder = "/storage/emulated/0/Download";

            // Verificamos que la carpeta exista
            if (Directory.Exists(downloadFolder))
            {
                // Copiamos el archivo grabado a la carpeta "Download"
                string destinationPath = Path.Combine(downloadFolder, videoFileName);
                File.Copy(videoPath, destinationPath, true);

                // Escaneamos el archivo para que aparezca en la galería
                using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                {
                    using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
                    {
                        using (AndroidJavaClass mediaScanner = new AndroidJavaClass("android.media.MediaScannerConnection"))
                        {
                            mediaScanner.CallStatic("scanFile", currentActivity, new string[] { destinationPath }, null, null);
                        }
                    }
                }

                Debug.Log($"Saved recording to: {destinationPath}");
            }
            else
            {
                Debug.LogError("La carpeta 'Download' no existe en la ruta especificada.");
            }
        }
    }
}

}

@Juanpabloh814 Juanpabloh814 added the bug Something isn't working label Aug 1, 2023
@yasirkula
Copy link
Owner

I'm guessing you're trying to save it without using NativeGallery in which case the only support I can provide is pointing you to NativeGallery's relevant source code: https://github.com/yasirkula/UnityNativeGallery/blob/fd69fa2ee62b3bc85ee87eda01ded7af5de76915/.github/AAR%20Source%20(Android)/java/com/yasirkula/unity/NativeGallery.java#L44-L302

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants