Play system sound while recording video/audio

2019-03-31 02:54发布

问题:

I'm trying to play a "beep" sound as required by apple when I start recording a video. I've found through SO and other sources that you can't play a sound while you have an audio input going without some configuration.

Here's my attempt at the configuration method:

private void SetupAudio()
    {
        beepSound = AssetBank.GetSystemSoundWav("video_record", "video_beep");
        AudioSession.Initialize();
        AudioSession.Interrupted += delegate
        {
            Console.WriteLine("Interrupted handler");
        };

        AudioSession.Category = AudioSessionCategory.PlayAndRecord;
        AudioSession.OverrideCategoryMixWithOthers = true;

        NSError err;
        AVAudioSession.SharedInstance().SetActive(true, out err);
    }

And here's my code where I setup the recording session:

public void SetupVideoCaptureSession(AVCaptureDevicePosition position)
    {

        // Setup devices
        foreach (var device in AVCaptureDevice.Devices)
        {
            if (device.HasMediaType(AVMediaType.Video))
            {
                if (device.Position == AVCaptureDevicePosition.Front)
                {
                    frontCam = device;
                } else if (device.Position == AVCaptureDevicePosition.Back)
                {
                    backCam = device;
                }
            }
        }

        // Create capture session
        captureSession = new AVCaptureSession();
        captureSession.BeginConfiguration();
        captureSession.SessionPreset = AVCaptureSession.Preset640x480;
        // Create capture device

        switch (position)
        {
            case AVCaptureDevicePosition.Back:
                videoDevice = backCam;
                break;

            case AVCaptureDevicePosition.Front:
                videoDevice = frontCam;
                break;
        }

        if (null == videoDevice)
        {
            using (var alert = new UIAlertView { Message = "No camera detected!" })
            {
                alert.AddButton("Okay!");
                alert.Show();
            }
            return;
        }

        audioDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Audio);

        // Create capture device input
        NSError videoError, audioError;
        videoDeviceInput = new AVCaptureDeviceInput(videoDevice, out videoError);
        audioDeviceInput = new AVCaptureDeviceInput(audioDevice, out audioError);

        captureSession.AddInput(videoDeviceInput);
        captureSession.AddInput(audioDeviceInput);

        // Create capture device output
        videoOutput = new AVCaptureMovieFileOutput();
        videoOutput.MaxRecordedDuration = new CMTime(10, 1);

        captureSession.AddOutput(videoOutput);

        if (null != previewLayer)
            previewLayer.RemoveFromSuperLayer();

        // Create preview layer
        previewLayer = AVCaptureVideoPreviewLayer.FromSession(captureSession);
        previewLayer.Orientation = AVCaptureVideoOrientation.Portrait;
        previewLayer.VideoGravity = "AVLayerVideoGravityResizeAspectFill";
        previewLayer.Frame = new RectangleF(new PointF(), ScreenSize);

        this.ParentScrollView.Layer.InsertSublayer(previewLayer, 0);

        // Start capture session

        SetupAudio();
        captureSession.CommitConfiguration();
        captureSession.StartRunning();
    }

No matter what I try, I can't get a sound to play after I've started the capture session. Anyone solved this in MonoTouch?

回答1:

This is what I use in The Harlem Shake:

AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.MediaPlayback;
AudioSession.OverrideCategoryMixWithOthers = true;

Then to turn it off, I do this:

AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.AmbientSound;
AudioSession.OverrideCategoryMixWithOthers = false;

This allows me to play "the Harlem Shake" with AVAudioPlayer during video capture. It also overrides the silent switch on the iDevice. I don't know if AudioSession.Initialize() is required on both parts, you might play around with just calling it once.



回答2:

After pulling my hair out all day yesterday, I got this working.

private void PlayBeepSound()
    {
        NSError err;
        var player = AVAudioPlayer.FromUrl(NSUrl
            .FromFilename("Sounds/video_record/video_beep.wav"), out err);
        player.Play();
    }

Before, I was attempting to use sound.PlaySystemSound(), which wasn't working. Switching to AVAudioPlayer allowed the sound to play. At least I learned a bunch about iPhone audio internals!



回答3:

Hi fellow developers here is the Objective C code for above problem,

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"VoicemailSound" ofType:@"mp3"]]; //Download and add a system sound to your project and mention its name and type here
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error: nil];

[self.audioPlayer prepareToPlay];
[self.audioPlayer play];