【问题标题】:iOS SDK : playing music on the background and switching viewsiOS SDK:在后台播放音乐并切换视图
【发布时间】:2012-01-18 01:07:06
【问题描述】:

我正在尝试在我的应用程序中播放音乐。音乐效果很好,但在切换 viewControllers 并返回主菜单后,我的音乐又开始播放了!这意味着几个相同的声音一起播放!我该如何解决这个问题?这是我的代码:

- (void)viewDidLoad {

    NSString *music = [[NSBundle mainBundle] pathForResource:@"1music" ofType:@"mp3"];
    myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
    myMusic.delegate = self;
    myMusic.numberOfLoops = -1; 
    [myMusic play];
}


- (IBAction) scoreView {

    ScoreViewController *scoreView = [[ScoreViewController alloc] initWithNibName:@"ScoreViewController" bundle:nil];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    [self.view addSubview: scoreView.view];
    [UIView commitAnimations];
}

编辑代码:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {

            NSString * musicSonati = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
            myMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicSonati] error:NULL];
            myMusic.delegate = self;
            myMusic.numberOfLoops = -1;
            [myMusic play];

        }
        return self;
    }

//toggle button
- (IBAction)MusicPlaying:(id)sender {

    if ((isPlay = !isPlay))
    {

        UIImage *buttonImageNormal = [UIImage imageNamed:@"play.png"]; 
        UIImage *stretchableButtonImageNormal = [buttonImageNormal  stretchableImageWithLeftCapWidth:0 topCapHeight:0]; 
        [MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; 
        [myMusic pause];



    }else {

        UIImage *buttonImageNormal = [UIImage imageNamed:@"pause.png"]; 
        UIImage *stretchableButtonImageNormal = [buttonImageNormal  stretchableImageWithLeftCapWidth:0 topCapHeight:0]; 
        [MusicButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; 
        NSLog(@"Music play");
        [myMusic play];

    } 

}

【问题讨论】:

  • 我有一个建议,即尝试从您的 appdelegate 文件中播放音乐,即使您切换视图也会播放

标签: iphone ios xcode ipad


【解决方案1】:

首先,viewDidLoad 可能不是初始化AVAudioPlayer 的好地方,因为系统可能需要卸载一些组件以回收内存(在viewDidUnload 中)。您可能应该在 init 方法或类似方法中创建 AVAudioPlayer

所以发生的情况是,当焦点回到您的应用程序时,您最终创建了第二个AVAudioPlayer,而您实际上失去了对第一个的引用。 (因此,也内存泄漏。

如果你想在视图加载时开始播放音乐,你应该在这样做之前另外检查它的状态:

- (void)viewDidLoad {
    ...
    if (!myMusic.playing) {
        [myMusic play];
    }
    ...
}

【讨论】:

  • 我把我的代码放在带有笔尖名称的初始化中......但是音乐没有播放!有什么问题?
  • 您将不得不发布更多代码,以及任何调试冒险的成果。除非您向我们提供其他信息,否则我们无法从这里猜测您的代码有什么问题。
  • 您确定您的视图控制器的init: 方法正在被调用吗? init: 调用 AVAudioPlayer 是否返回错误? (不要忽视它!)
  • 我不知道如何以及在哪里调用init: 方法
  • 视图控制器的初始化可能很棘手。我通常使用一个 commonInit 并覆盖所有的 init 方法来调用它。例如,如果您使用界面构建器嵌套/卸载视图,则会调用 initWithCoder。让我发布一个答案,而不是试图在评论中解决这个问题。
【解决方案2】:

如果您要在多个地方播放音频,那么实现此目的的一种简单方法是在委托中声明 AVAudioPlayer 实例,并使用综合属性。如果您想在任何地方播放,请执行以下操作:-

MyAppDelegate *app_delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];


if(app_delegate.audioPlayer)
{
    [app_delegate.audioPlayer release];
    app_delegate.audioPlayer = nil;
}
app_delegate.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];     

如果您想停止声音,请执行以下操作:-

if(app_delegate.audioPlayer)
{
    if([app_delegate.audioPlayer isPlaying])
    {
        [app_delegate.audioPlayer stop];
        [app_delegate.audioPlayer setCurrentTime:0];
    }
}

如果已经分配或使用新的声音文件 url 再次分配,则播放新的声音文件版本和 nil 相同的播放器。

【讨论】:

  • +1。如果你打算使用 AVAudioPlayer,这是要走的路。应该只在应用程序中出现一次的东西应该在单例中,并且您已经有了一个非常好的东西:您的 AppDelegate。
【解决方案3】:

看来您正在开发游戏(来自您的函数名称 After viewLoad (ScoreView). ;))

好吧,在我看来,如果你想用 Game 来实现,AvAudioplayer 并不是一个好选择。

使用cocosdenshion,下载最新的cocos2d文件夹,找到这9个文件,放到你的资源文件夹中,

你已经完成了.. !!!

#import "SimpleAudioEngine.h" // wherever you want to call in head part of the file.

Step1 调用短文件!

[[SimpleAudioEngine sharedEngine] playEffect:@"blast.mp3"];

step2 调用后台循环。

[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"background.mp3" loop:YES];

注意:有可用功能列表http://www.cocos2d-iphone.org/api-ref/0.99.5/interface_simple_audio_engine.html,非常简单!

整个实施过程最多需要 20 分钟!

【讨论】:

    【解决方案4】:

    在应用委托文件中初始化您的播放器并播放您的背景音乐。只需在应用程序委托中设置一个变量来检查音乐播放的真假……并在不重新启动音乐的情况下享受您的应用程序……

    在您的代码中,您在视图中初始化播放器并加载和 init 方法...这就是为什么您重新启动音乐.....只需在应用程序委托 applicationdidfinshLaunching() 方法中调用它一次....

    【讨论】:

      【解决方案5】:

      确保 myMusic 被正确声明为保留属性并合成,然后尝试如下操作:

      -(void) commonInit {
          NSString * musicSonati = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
          self.myMusic = [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:musicSonati] error:NULL] autorelease];
          self.myMusic.delegate = self;
          self.myMusic.numberOfLoops = -1;
      //You probably don't want to play music on init, rather defer to viewDidLoad.
      //        [self.myMusic play];
      }
      
      - (id)initWithCoder:(NSCoder *)coder {
          self = [super initWithCoder:coder];
          if (self) {
              [self commonInit];
          }
          return self;
      }
      
      - (id)init {
          self = [super init];
          if (self) {
              [self commonInit];
          }
          return self;
      }
      
      - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
          if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
              [self commonInit];
          }
          return self;
      }
      

      然后在你的 viewDidLoad 中试试这个:

      - (void)viewDidLoad {
          ...
          if (!self.myMusic.playing) {
              [self.myMusic play];
          }
          ...
      }
      

      另外,不要忘记在 dealloc 中释放你的播放器!

      【讨论】:

      • 谢谢,我的问题是切换按钮不能正常工作
      猜你喜欢
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多