objective-c 如何将 AVAudioPlayer 输出到扬声器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1022992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:45:41  来源:igfitidea点击:

How to get AVAudioPlayer output to the speaker

iphoneobjective-caudioavaudioplayeravaudiorecorder

提问by dizy

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

我正在使用 AVAudioRecorder 录制音频,如如何使用 AVAudioRecorder 在 iPhone 上录制音频中所示?

I then use AVAudioPlayer to play back the recording. However the sound is coming out of the ear speaker, not the loud speaker. How would I go about redirecting the sound to the loud speaker ?

然后我使用 AVAudioPlayer 播放录音。然而,声音是从耳机传出来的,而不是外放。我将如何将声音重定向到扬声器?

TIA!

蒂亚!

采纳答案by dizy

From http://www.iphonedevsdk.com/forum/iphone-sdk-development-advanced-discussion/12890-audiosessionsetproperty-problem-playing-sound-listening-mic.html--

来自http://www.iphonedevsdk.com/forum/iphone-sdk-development-advanced-discussion/12890-audiosessionsetproperty-problem-playing-sound-listening-mic.html--

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);    
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

回答by Daniel

I realize this question is fairly old but when I was struggling with the same problem I found a simple solution that hopefully will help anyone else looking to use the louder media speakers as opposed to the receiver speakers. The method I used was setting up the audio session with the DefaultToSpeaker option in AVAudioSessionCategoryOptions:

我意识到这个问题已经很老了,但是当我遇到同样的问题时,我找到了一个简单的解决方案,希望能帮助其他人希望使用更大声的媒体扬声器而不是接收器扬声器。我使用的方法是使用 AVAudioSessionCategoryOptions 中的 DefaultToSpeaker 选项设置音频会话:

In Swift (assuming your audio session is named session) -

在 Swift 中(假设您的音频会话名为session) -

session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker, error: nil)

In Obj-C -

在 Obj-C 中 -

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

回答by budidino

Swift 3

斯威夫特 3

Before recording the sound I set:

在录制我设置的声音之前:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)

and before playback I set:

在播放之前我设置了:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

Objective C

目标 C

before recording:

录音前:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryRecord error:nil];

before playback:

播放前:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

回答by Spencer Powell

This works great for me in Swift2

这在 Swift2 中对我很有用

let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)

回答by Simo A.

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 .

该解决方案在以下博客文章中进行了描述:iOS:插入耳机时强制音频输出到扬声器

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

您需要在您的项目中创建新的 Objective-C 类 AudioRouter。然后导入AudioRouter.h到您正在启动音频功能的类的头文件中。接下来,在相应的.m文件中,在viewDidLoad方法中添加以下几行:

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 whilethe app is running, then all audio output is directed to earphones.

现在您将音频(例如 AVAudioPlayer)输出强制到扬声器!请注意,如果您在应用程序运行插入耳机,则所有音频输出都将定向到耳机。

回答by Kristian

Swift2:

斯威夫特2:

try session.setCategory(AVAudioSessionCategoryPlayAndRecord,
    withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)

回答by Mc.Lover

Swift 3

斯威夫特 3

 let audioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
    } catch let error as NSError {
        print("Audio Session error: \(error.localizedDescription)")
    }

回答by Ali Pishvaee

Answer For Swift 4.0

Swift 4.0 的答案

func SetSessionPlayerOn()
{
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch _ {
    }
    do {
        try AVAudioSession.sharedInstance().setActive(true)
    } catch _ {
    }
    do {
        try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
    } catch _ {
    }
}
func SetSessionPlayerOff()
{
    do {
        try AVAudioSession.sharedInstance().setActive(false)
    } catch _ {
    }
}

回答by Spydy

this is the key line to output auido in speaker instead in microphone. Note it should be set while recording

这是在扬声器而不是麦克风中输出音频的关键线。注意它应该在录制时设置

try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)

Below is complete function to setup recording

以下是设置录音的完整功能

private func setupRecorder() {

    if isAudioRecordingGranted {
        let session = AVAudioSession.sharedInstance()
        do {

            if #available(iOS 10.0, *) {
                try! session.setCategory(.playAndRecord, mode:.spokenAudio)
            }
            else {
                // Workaround until https://forums.swift.org/t/using-methods-marked-unavailable-in-swift-4-2/14949 isn't fixed
               session.perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
            }
            try session.setActive(true)
            try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)

            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
            ]
            audioRecorder = try AVAudioRecorder(url: fileUrl(), settings: settings)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            audioRecorder.prepareToRecord()
            self.recorderState = .Ready
        }
        catch let error {
            recorderState = .error(error)
        }
    }
    else {
        recorderState = .Failed("Don't have access to use your microphone.")
    }
}

回答by keishinzzz

Swift 5

斯威夫特 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 Documentationfor more information about AVAudioSession.CategoryOptions.

查看开发者文档了解更多关于AVAudioSession.CategoryOptions 的信息。