How to get AVAudioPlayer output to the speaker

前端 未结 10 1705
孤城傲影
孤城傲影 2020-12-07 14:29

I\'m recording audio with AVAudioRecorder as seen in How do I record audio on iPhone with AVAudioRecorder?

I then use AVAudioPlayer to play back the recording. Howev

相关标签:
10条回答
  • 2020-12-07 15:26

    Swift2:

    try session.setCategory(AVAudioSessionCategoryPlayAndRecord,
        withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)
    
    0 讨论(0)
  • 2020-12-07 15:28

    This is an old question, but the other answer did not help me... However, I found a solution which I am posting for future reference in case someone (or myself from the future!) needs it.

    The solution is described in the following blog post: iOS: Force audio output to speakers while headphones are plugged in .

    You need to create new Objective-C class AudioRouter in your project. Then import AudioRouter.h into your header file of the class where you are initiating audio functionality. Next, in the corresponding .m file add the following lines within viewDidLoad method:

    AudioRouter *foobar = [[AudioRouter alloc] init];
    [foobar initAudioSessionRouting];
    [foobar forceOutputToBuiltInSpeakers];
    

    Now you have audio (e.g. AVAudioPlayer) output forced to loudspeaker! Note that if you plug in earphones while the app is running, then all audio output is directed to earphones.

    0 讨论(0)
  • 2020-12-07 15:32

    Swift 5

    // Get the singleton instance.
    let recordingSession = AVAudioSession.sharedInstance()
    do {
        // Set the audio session category, mode, and options.
        try recordingSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
        try recordingSession.setActive(true)
    } catch {
        print("Failed to set audio session category.")
    }
    

    Check the Developer Documentation for more information about AVAudioSession.CategoryOptions.

    0 讨论(0)
  • 2020-12-07 15:33

    Swift 3

     let audioSession = AVAudioSession.sharedInstance()
    
        do {
            try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
        } catch let error as NSError {
            print("Audio Session error: \(error.localizedDescription)")
        }
    
    0 讨论(0)
提交回复
热议问题