停止 AVAudioPlayer

发布于 2024-10-28 05:51:11 字数 833 浏览 0 评论 0原文

这是我的代码

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"95" ofType:@"wav"];

NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];

NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];

if (musicPlayer1) {
    [musicPlayer1 stop];
    [musicPlayer1 release];
    musicPlayer1 = nil;
}
else {

    [musicPlayer1 prepareToPlay];
    [musicPlayer1 setVolume:.8];
    [musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
    [musicPlayer1 setDelegate: self];
    [musicPlayer1 play];
}

}

我正在尝试使用相同的按钮启动和停止 AVAudioPlay(musicPlayer1 在标题中)。现在,当我触摸按钮时,它不会播放任何内容。请帮忙?

here is my code

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"95" ofType:@"wav"];

NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];

NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];

if (musicPlayer1) {
    [musicPlayer1 stop];
    [musicPlayer1 release];
    musicPlayer1 = nil;
}
else {

    [musicPlayer1 prepareToPlay];
    [musicPlayer1 setVolume:.8];
    [musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
    [musicPlayer1 setDelegate: self];
    [musicPlayer1 play];
}

}

I am rying to start and stop the AVAudioPlay with the same button (musicPlayer1 is in the header). Now when i touch the button it does not play anything. Help please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉墨 2024-11-04 05:51:11

您每次都会创建一个新的 AVAudioPlayer 实例。您需要在某处保留对该对象的引用,然后再引用该对象。将字段添加到视图控制器类:

@private AVAudioPlayer *currentAudio;

然后在此方法中进行以下更改:

if (currentAudio) {
    [currentAudio stop];
    [currentAudio release];
    currentAudio = nil;
} else {
    // what you already have goes here
}

You're creating a new instance of AVAudioPlayer each time. You need to hold onto the reference to the object somewhere, and refer back to that. Add a field to your view controller class:

@private AVAudioPlayer *currentAudio;

And then in this method, make the following changes:

if (currentAudio) {
    [currentAudio stop];
    [currentAudio release];
    currentAudio = nil;
} else {
    // what you already have goes here
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文