iOS - 打电话时在后台播放声音

iOS - Playing sound in background when making a call

我在 Obj-C 中有一个可以拨打电话的应用程序,我想在用户按下按钮开始通话时播放声音。 通话时会一直在后台播放声音吗? 如果是这样,我该如何实现?

先谢谢你

在 .car 中查找声音或像这样使用默认值

@property (assign) SystemSoundID pewPewSound;
@property (nonatomic) NSArray * soundArray;

self.soundArray = @[@"DECKALRM",@"LOW_GONG10"];

// sound - url path to your sound,(NSString*)[self.soundArray objectAtIndex:0];
// @"DECKALRM" - you custom sound name in your project

NSURL * pewPewURL = [[NSBundle mainBundle]URLForResource:sound withExtension:@"caf"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL, &_pewPewSound);
AudioServicesPlaySystemSound(self.pewPewSound);

停止声音

AudioServicesRemoveSystemSoundCompletion(self.pewPewSound);
AudioServicesDisposeSystemSoundID(self.pewPewSound);

例如尝试 this sound

运营商 phone 呼叫正在进行时,绝对无法播放声音。

Sometimes, currently playing audio is interrupted by audio from a different app. On iPhone, for example, an incoming phone call interrupts the current app’s audio for the duration of the call. In a multitasking environment, the frequency of such audio interruptions can be high.

这与拨出 phone 呼叫的行为相同。它会在通话期间中断当前应用程序的音频 (playing/recording)。

您可以在此处阅读更多内容:iOS Human Interface Guide

请尝试此代码,这将在通话过程中播放背景音。

但这有一个问题,它会在接收端产生回声。

请分享您的反馈并尝试解决回声问题

编码愉快 :)

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:self.bgAudioFileName ofType: @"mp3"];    

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];

myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];

myAudioPlayer.numberOfLoops = -1;

 NSError *sessionError = nil;

    // Change the default output audio route

 AVAudioSession *audioSession = [AVAudioSession sharedInstance];

 // get your audio session somehow

 [audioSession setCategory:AVAudioSessionCategoryMultiRoute error:&sessionError];



BOOL success= [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&sessionError];

[audioSession setActive:YES error:&sessionError];
    if(!success)
    {
        NSLog(@"error doing outputaudioportoverride - %@", [sessionError localizedDescription]);
    }
    [myAudioPlayer setVolume:1.0f];
    [myAudioPlayer play];
}

创建一个 AudioSession 并按照以下方式播放音频文件-希望它适合你!

func playBackgroundAudioSample() {
    let path = Bundle.main.path(forResource:"Morningsun", ofType: "mp3")
    
    self.customAudioSession = AVAudioSession()
    do {
        self.customAudioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))
        try self.customAudioSession?.setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth, .allowBluetoothA2DP, .mixWithOthers])
        self.customAudioPlayer?.play()
        print("Playback OK")
    }
    catch let error {
        print("Error while playing Bg sound:\(error)")
    }
}