录制视频/音频时播放系统声音

4

我想在开始录制视频时按照苹果的要求播放"蜂鸣"声。通过Stack Overflow和其他来源,我发现如果你有正在进行的音频输入,就不能播放声音,除非进行一些配置。

这是我尝试的配置方法:

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);
    }

这是我设置录制会话的代码:

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();
    }

无论我尝试什么,都无法在启动捕获会话后播放声音。有人在MonoTouch中解决了这个问题吗?
3个回答

5

以下是我在The Harlem Shake中所使用的技术:

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

然后要关闭它,我会这样做:
AudioSession.Initialize();
AudioSession.Category = AudioSessionCategory.AmbientSound;
AudioSession.OverrideCategoryMixWithOthers = false;

这使我能够在视频捕获期间使用AVAudioPlayer播放“Harlem Shake”歌曲。它还覆盖了iDevice上的静音开关。我不知道是否需要在两个部分上都调用AudioSession.Initialize(),您可以尝试只调用一次。

谢谢回复。我已经想出了一个解决方案,准备发布它。 - Kiefer Hagin
@jonathanpeppers 那通话中断怎么办……卡在通话中断上了。 - Bhavin Bhadani
在你的AppDelegate中当应用程序转到后台或者被停用时,我会使用上面的代码来关闭它。 - jonathanpeppers

2

昨天我烦恼了一整天,终于弄好了这个。

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

之前,我尝试使用sound.PlaySystemSound(),但它无法正常工作。改用AVAudioPlayer后,声音得以播放。至少我学到了很多关于iPhone音频内部的知识!


1

大家好,这里是针对上述问题的Objective C代码:

@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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接