Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

ios - How to Play a sound using AVAudioPlayer when in Silent Mode in iPhone

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

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

(For ios 3.0+)

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

UPDATE (11/6/2013)

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. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...