【问题标题】:how to play only one sound at a time with AVAudioplayer如何使用 AVAudioplayer 一次只播放一种声音
【发布时间】:2011-02-11 05:33:05
【问题描述】:

当用户点击相关按钮时,我正在播放声音。

我有 10 个按钮和 10 个音频文件。

我正在使用 AVAudioPlayer 播放选定的声音

AVAudioPlayer *myaudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[sounds objectAtIndex:button.tag] ofType:@"mp3"]]error:NULL];
[myaudio play];

现在我有一个问题,如果我在完成播放上一个声音之前单击另一个按钮,那么两种声音都会混合并产生噪音。

我需要在完成第一个声音后播放第二个声音。

我的意思是一次只会播放一种声音。

我该怎么做,谁能帮帮我。

如果这个问题无法理解,让我添加评论。

提前谢谢你。

【问题讨论】:

    标签: iphone


    【解决方案1】:

    我这样解决我的问题

    if (soundplay == 0) {
            myaudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[sounds objectAtIndex:x] ofType:@"mp3"]]error:NULL];
            myaudio.delegate = self;
            soundplay = 1;
            [myaudio play];
        }
    
    - (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *)myaudio successfully:(BOOL)flag {
        soundplay = 0;
        NSLog(@"sound fnished");
    }
    

    其中声音播放是整数变量

    【讨论】:

    • 但是如果我点击按钮一次它会开始播放声音..如果我再次点击它然后它会开始不同的声音实例有间隙....我不想禁用按钮... . 那么我怎么能处理第二次点击.. ???
    【解决方案2】:

    @Mahesh 你可以创建一个AVAudioPlayer 类变量,在 IBAction 函数中你可以这样做:

    if([myaudio playing])
         [myaudio stop];
    myaudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[sounds objectAtIndex:button.tag] ofType:@"mp3"]]error:NULL];
    [myaudio play];
    

    【讨论】:

      【解决方案3】:

      不要创建不同的 AVAudioPlayer 对象。为 AVAudioPlayer 创建单音对象。并使用此对象只需检查该对象播放器是否正在播放。

      if([myaudio playing])
      {
          [myaudio stop];
          myaudio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle     mainBundle]pathForResource:[sounds objectAtIndex:button.tag] ofType:@"mp3"]]error:NULL];
          [myaudio play];
      }
      

      【讨论】:

      • 我收到警告:“AVAudioPlayer”可能无法响应“-playing”并且应用程序退出
      • 参见 iOS 参考库中的示例代码 avTouch 以供参考。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多