如果打开静音按钮,如何播放音频?

时间:2013-02-03 22:00:09

标签: objective-c uibutton avfoundation avaudioplayer avaudiosession

点击按钮时,我正在尝试播放音频文件。

如果我单步执行我的代码就行了,但是如果我只是点击按钮就没有声音播放。

这是我的代码:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
AVAudioPlayer * player;
NSString * path = [[NSBundle mainBundle] pathForResource:@"soundOne" ofType:@"mp3"];
NSURL * url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[player play];

这是播放音频的合适方式吗?没有任何东西被标记为被弃用。

我也在调试器中看到此消息:

AudioQueue: request to trim 0 + 2690 = 2690 frames from buffer containing 1152 frames

编辑:

此代码有效。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"soundOne"
                                                     ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
                    initWithContentsOfURL:fileURL error:nil];
[self.audioPlayer prepareToPlay];
self.audioPlayer.currentTime = 0;
[self.audioPlayer play];

如何使用静音按钮播放音频?

以下是我为此尝试过的代码:

CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus audioStatus = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if (audioStatus == kAudioSessionNoError) {
    //NSLog(@"audio route: %@", state);
    return (CFStringGetLength(state) <+ 0);
}
return NO;

1 个答案:

答案 0 :(得分:3)

在你打电话之前坚持这个:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

应该这样做。

相关问题