Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

objective c - Play sound on iPhone even in silent mode


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

1 Answer

0 votes
by (71.8m points)

It's not advisable, but who am I to say you can't do it. You may have a good reason to be playing sound.

If you are using Audio Sessions, then include <AVFoundation/AVFoundation.h> at the start of your file and

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

should do the trick. Note if you play music or sounds, then iPod playback will be paused.

Once this has been done, probably somewhere in the initialization of one of your classes that plays the sounds, you can instantiate sounds like this:

// probably an instance variable: AVAudioPlayer *player;
NSString *path = [[NSBundle mainBundle] pathForResource...];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url];

When that's done, you can play with it any time you want with:

[player play]; // Play the sound
[player pause]; // Pause the sound halfway through playing
player.currentTime += 10 // skip forward 10 seconds
player.duration // Get the duration

And other nice stuff. Look up the AVAudioPlayer Class reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...