声音在音板中停止工作(Xcode)

发布于 2024-12-04 19:44:22 字数 602 浏览 0 评论 0原文

在我的音板应用程序中,一段时间后声音将停止工作,直到应用程序关闭并再次打开。无法弄清楚出了什么问题!这是我的代码:

在 .h 文件中:

(imported files here)

@interface MainView : UIView {

}
- (IBAction)pushButton2:(id)sender;

@end

在 .m 文件中:

(imported files here)


@implementation MainView

- (IBAction)pushButton2:(id)sender {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];

}

@end

In my soundboard app, after some time the sound will stop working until the app is closed and opened again. Can't figure out what is wrong! here is my code:

In the .h file :

(imported files here)

@interface MainView : UIView {

}
- (IBAction)pushButton2:(id)sender;

@end

In the .m file:

(imported files here)


@implementation MainView

- (IBAction)pushButton2:(id)sender {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];

}

@end

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

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

发布评论

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

评论(1

卷耳 2024-12-11 19:44:23

我不确定它会导致您所看到的行为,但每次按下按钮时您肯定都会泄漏 AVAudioPlayer 。此外,我只会加载一次(例如,在 viewDidLoad 中),而不是在每次按下按钮时加载。也许是这样的:

@interface MainView : UIView
{
    AVAudioPlayer* audioPlayer;
}
- (IBAction)pushButton2:(id)sender;
@end

@implementation MainView

- (void) viewDidLoad
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    audioPlayer.delegate = self;

}

- (void) viewDidUnload
{
    [audioPlayer release], audioPlayer = nil;
}

- (IBAction)pushButton2:(id)sender 
{
    [audioPlayer play];
}

@end

I'm not sure it would cause the behavior you're seeing, but you're definitely leaking the AVAudioPlayer each time the button is pressed. Additionally, I would just load it once (say, in viewDidLoad), rather than on each button press. Perhaps something like:

@interface MainView : UIView
{
    AVAudioPlayer* audioPlayer;
}
- (IBAction)pushButton2:(id)sender;
@end

@implementation MainView

- (void) viewDidLoad
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    audioPlayer.delegate = self;

}

- (void) viewDidUnload
{
    [audioPlayer release], audioPlayer = nil;
}

- (IBAction)pushButton2:(id)sender 
{
    [audioPlayer play];
}

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文