如何在iPhone中处于静音模式时使用AVAudioPlayer播放声音 [英] How to Play a sound using AVAudioPlayer when in Silent Mode in iPhone

查看:375
本文介绍了如何在iPhone中处于静音模式时使用AVAudioPlayer播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iPhone中以静音模式播放声音。

I want to play a sound even in silent mode in iPhone.

可以使用AVAudioPlayer完成(不使用AVAudioSession)

Can it be done by using AVAudioPlayer (Without using AVAudioSession)

(适用于ios 3.0 +)

(For ios 3.0+)

提前致谢。

推荐答案

实际上,你可以这样做。它通过音频会话控制,与 AVAudioPlayer 本身无关。你为什么不想使用AudioSession?他们一起玩得很好......

Actually, you can do this. It is controlled via the Audio Session and has nothing to do with AVAudioPlayer itself. Why don't you want to use AudioSession? They play nice together...

在你的应用程序中,你应该初始化音频会话,然后你也可以告诉你打算播放什么样的音频。如果您是音乐播放器,那么即使启用了响铃/静音开关,用户也希望听到音频

In your app, you should initialize the Audio Session, and then you can also tell indicate what kind of audio you intend to play. If you're a music player, then it sort of makes sense that the user would want to hear the audio even with the ring/silent switch enabled.

    AudioSessionInitialize (NULL, NULL, NULL, NULL);
    AudioSessionSetActive(true);

    // Allow playback even if Ring/Silent switch is on mute
    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, 
                             sizeof(sessionCategory),&sessionCategory);

我有一个应用程序,我做这件事,并使用AVAudioPlayer播放音频,并与启用了响铃/静音开关,我可以听到音频。

I have an app that I do this very thing, and use AVAudioPlayer to play audio, and with the ring/silent switch enabled, I can hear the audio.

更新(2013年6月11日)

在我上面提到的应用程序中,我成功地使用了上面的代码,我(有一段时间)使用以下代码来实现相同的结果:

In the app I mentioned above, where I used the code above successfully, I have (for some time) been using the following code instead to achieve the same result:


        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *error = nil;
        BOOL result = NO;
        if ([audioSession respondsToSelector:@selector(setActive:withOptions:error:)]) {
            result = [audioSession setActive:YES withOptions:0 error:&error]; // iOS6+
        } else {
            [audioSession setActive:YES withFlags:0 error:&error]; // iOS5 and below
        }
        if (!result && error) {
            // deal with the error
        }

        error = nil;
        result = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];

        if (!result && error) {
            // deal with the error
        }

根据对此答案的最新评论,我认为我会将此作为替代方案发布。 : - )

I thought I'd post this as an alternative, in light of the most recent comment to this answer. :-)

这篇关于如何在iPhone中处于静音模式时使用AVAudioPlayer播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆