【问题标题】:AVAudioPlayer sound file location not changing / updatingAVAudioPlayer 声音文件位置未更改/更新
【发布时间】:2013-03-11 07:07:08
【问题描述】:

*这是我的第一个 stackoverflow 问题,如果我做错了什么,敬请见谅。

我正在尝试创建一个简单的音板应用程序。我无法让我的 AVAudioPlayer 在 xCode 4.1 (iOS 6.1.2) 上更新要播放的声音文件的位置。我想避免使用多个音频播放器(audioPlayer2、audioPlayer3 等),所以我尝试使用相同的音频播放器,而是更新声音文件所在的位置。我只想一次播放一个声音,所以多个声音显然不是问题。这是我的代码:

- (IBAction)play {
 if (audioPlayer.playing == NO) {
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/k.mp3", [[NSBundle mainBundle] resourcePath]]];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;

    //I added the next two lines to allow me to play AVAudio with MPiPodPlayer (which I found on this site, too) simultaneously.
    AVAudioSession *audiosession = [AVAudioSession sharedInstance];
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];

    [audioPlayer play];
    [start setTitle:@"Stop" forState:UIControlStateNormal];
}
 else
     if (audioPlayer.playing == YES) {
         [audioPlayer stop];
     [start setTitle:@"Start" forState:UIControlStateNormal];
    }
    }


- (IBAction)play2 {
if (audioPlayer.playing == NO) {
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/chicken.mp3", [[NSBundle mainBundle] resourcePath]]];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;

    AVAudioSession *audiosession = [AVAudioSession sharedInstance];
    [audiosession setCategory:AVAudioSessionCategoryAmbient error:nil];

    [audioPlayer play];
    [start2 setTitle:@"Stop" forState:UIControlStateNormal];
    clicked = 1;
    clicked2 = 0;
} else
    if (audioPlayer.playing == YES) {
        [audioPlayer stop];
        [start2 setTitle:@"Start" forState:UIControlStateNormal];
        clicked = 0;
    }
}

我的 IBActions 链接到 UIButtons 并且“开始”是 UIButton 引用。每当我点击“开始”时,它会播放“k.mp3”,但是如果我在开始播放“k.mp3”文件而不是鸡肉文件之后点击“start2”。我首先点击的按钮是 url 设置的。这是我的第一个 iPhone OS 应用程序项目,所以我意识到其中可能存在一些令人尴尬的编码错误(请随时纠正我)。我想要一个适用于多个按钮的答案,即使是大约 30 个按钮,所以我不必为每个按钮复制和粘贴停止音频播放器 1、2 和 3。

总结一下:我有多个按钮,每个按钮播放一种声音,我希望一次播放的声音不超过一种;当我单击一个按钮时,它会播放 1 种声音,并且所有其他音频播放器都会停止。为了简单起见,我宁愿只有一个 AVAudioPlayer 实例。提前致谢!

【问题讨论】:

    标签: ios objective-c xcode avaudioplayer


    【解决方案1】:

    检查应用程序控制是否进入- (IBAction)play2

    如果控制进入其中但仍然无法正常工作,那么您可以在此之前尝试[audioPlayer release]

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    

    这可能对你有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多