首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >背景音乐

背景音乐
EN

Stack Overflow用户
提问于 2012-05-02 02:53:29
回答 1查看 550关注 0票数 0

(使用AVFoundation.framework)

代码语言:javascript
复制
#import "AVFoundation/AVFoundation.h"

所以我遇到了一个问题,我首先在我的类的init方法中尝试了这个代码(也就是首先加载的那个)。

代码语言:javascript
复制
NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops=-1;
[player play];

但它不起作用,所以我决定在线程中:在init方法中:

代码语言:javascript
复制
[NSThread detachNewThreadSelector:@selector(playMusic) toTarget:self withObject:nil];

和方法本身:

代码语言:javascript
复制
-(void) playMusic {
    NSString* soundFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
    NSURL* soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    player.numberOfLoops=-1;
    [player play];
}

它当然是在*.h文件中声明的。它也不起作用。

我试着调试,在网上

代码语言:javascript
复制
}

对于playMusic方法,文件会播放2到3秒,然后停止。如果没有debug,就不能播放。有什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-02 03:03:56

AVAudioPlayer将被立即释放。你需要留住球员。因此,将AVAudioPlayer设置为该类的实例变量。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10402645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档