2011-06-15 88 views
0

我使用AudioPlayer停止所有播放的代码给出我可以停止播放用我的应用程序

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]]; 

NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
audioPlayer.numberOfLoops = -1; 

if (audioPlayer == nil) 
    NSLog([error description]);    
else 
    [audioPlayer play]; 

但我可以停止所有播放用这个,但不能再次发挥停止打边后卫。我怎样才能做到这一点,请帮助

回答

3

您可以轻松播放暂停停止你AVAudioPlayer用这三种方法:

- (void)pause 
- (void)stop 
- (BOOL)play //Returns YES on success, or NO on error. 

如果暂停,然后你可以发挥你从何处暂停恢复。

希望这可以帮助,我真的不知道你的问题在哪里!


在你给的代码

,你是不是暂停,你只是用numberOfLoops负播放。 你应该有一个方法来启动你的音乐是这样的:

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]]; 

NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
audioPlayer.numberOfLoops = 0;//play once 

if (audioPlayer == nil) 
    NSLog([error description]);    
else 
[audioPlayer prepareToPlay];   
[audioPlayer play]; 

,另一个是暂停:

[audioPlayer pause]; 

,另一个用于恢复:

[audioPlayer play]; 

要切换的iPod音乐,当应用程序启动和退出覆盖这两种方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    MPMusicPlayerController  *musicPlayer; 
    MPMusicPlaybackState playbackState = [musicPlayer playbackState]; 
    if (playbackState == MPMusicPlaybackStatePlaying) { //simple verification 
     [musicPlayer pause]; 
    } 
} 

- (void)applicationWillResignActive:(UIApplication *)application 

    if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {//simple verification 
     [musicPlayer play]; 
} 
    } 

希望它终于适合您的需求!

+0

看,我在听音乐,我运行我的应用程序应该停止所有播放,但是当我点击屏幕时自动播放开始, – Ali 2011-06-15 18:50:48

+0

您是否暂停所有您开始的播放?或者你的意思是iPod.app音乐? – 2011-06-15 19:00:31

+0

是的,我可以使用上面的技巧暂停所有播放但不能恢复它 – Ali 2011-06-15 19:02:30

相关问题