0

我正在开发一个应用程序,用户可以在其中从设备库中选择一个声音文件,它会在应用程序运行时开始在应用程序后台播放。一旦选择,它将在每次应用程序运行时运行,直到用户再次浏览并更改声音文件。

我需要将声音文件复制到应用程序吗?或者它可以只使用它的路径来完成。

请让我知道是否有人可以帮助我。

4

1 回答 1

0

这些是请求动作的代码,appSoundPlayer 是在 h 文件中声明的 AVAudioPlayer 的一个属性。此示例还播放资源文件夹中的歌曲。

我按照我的要求这样做了,您想在后台播放它,因此您需要进行一些更改并在 didFinishLaunchingWithOptions 中播放并在 applicationWillTerminate 中停止它也考虑到这两种方法 applicationDidEnterBackground applicationWillEnterForeground

#pragma mark -
    #pragma mark *play*
    - (IBAction) playaction {

        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"];
        NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
        self.soundFileURL = newURL;
        [newURL release];
        [[AVAudioSession sharedInstance] setDelegate: self];
        [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];

    // Registers the audio route change listener callback function
    AudioSessionAddPropertyListener (
                                     kAudioSessionProperty_AudioRouteChange,
                                     audioRouteChangeListenerCallback,
                                     self
                                     );

    // Activates the audio session.

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

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
    self.appSoundPlayer = newPlayer;
    [newPlayer release];
    [appSoundPlayer prepareToPlay];
    [appSoundPlayer setVolume: 1.0];
    [appSoundPlayer setDelegate: self];
    [appSoundPlayer play];


    [stopbutton setEnabled:YES];
    [playbutton setEnabled: NO];
    playbutton.hidden=YES;
    pausebutton.hidden =NO;
}//playbutton touch up inside

#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
    [appSoundPlayer pause];
    pausebutton.hidden = YES;
    resumebutton.hidden = NO;

}//pausebutton touch up inside

#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
    [appSoundPlayer prepareToPlay];
    [appSoundPlayer setVolume:1.0];
    [appSoundPlayer setDelegate: self];
    [appSoundPlayer play];
    playbutton.hidden=YES;
    resumebutton.hidden =YES;
    pausebutton.hidden = NO;

}//resumebutton touch up inside

#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{

    [appSoundPlayer stop];
    [playbutton setEnabled:YES];
    [stopbutton setEnabled:NO];
    playbutton.hidden=NO;
    resumebutton.hidden =YES;
    pausebutton.hidden = YES;

}//stopbutton touch up inside
于 2013-05-07T13:34:51.757 回答