我正在使用 systemMusicPlayer
在应用内播放歌曲。
如果用户在“正在播放” View 上按下 noiseButton
,它将暂停 systemMusicPlayer
歌曲音频文件 10 秒以播放 noiseButton
音频文件,然后在 systemMusicPlayer
歌曲音频文件上拾取。
我能够让 systemMusicPlayer
歌曲音频文件暂停,然后在 10 秒后恢复,但我无法获得 noiseButton
在 10 秒内播放声音。
- 我知道
noiseButton
音频文件有效 - 我在播放
noiseButton
文件的方法之前和之后进行NSLog
ging
我不确定我错过了什么?
这是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
musicPlayer = [MPMusicPlayerController systemMusicPlayer];
[self registerMediaPlayerNotifications];
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:@"%@/background-music-aac.caf", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}
- (void)willPlayClip {
[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(willPlayMusicInTenSeconds:)
userInfo:nil
repeats:NO];
}
- (void)willPlayMusicInTenSeconds:(NSTimer *)timer {
NSLog(@"Get ready to Play noise sound");
[_audioPlayer play];
NSLog(@"Play noise sound");
[musicPlayer play];
NSLog(@"Start playing again");
}
以及 noiseButton
内按下时的代码:
if ([musicPlayer playbackState] == MPMusicPlaybackStatePlaying) {
[musicPlayer pause];
NSLog(@"Paused!");
[self willPlayClip];
} else {
NSLog(@"Already paused");
}
最佳答案
您要设置什么 AudioSession 类别?如果不是,请参阅此文档:
我相信,如果您将 session 设置为 AVAudioSessionCategoryAmbient
,您应该会获得所需的行为:
The category for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.
This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays while the Music app is playing. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).
如果您还没有尝试过,请尝试一下。
关于ios - 暂停音频文件以播放不同的音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449389/